github.com/sohaha/zlsgo@v1.7.13-0.20240501141223-10dd1a906f76/zstring/regex_test.go (about)

     1  package zstring
     2  
     3  import (
     4  	"regexp"
     5  	"testing"
     6  
     7  	"github.com/sohaha/zlsgo"
     8  )
     9  
    10  func TestExtract(t *testing.T) {
    11  	tt := zlsgo.NewTest(t)
    12  	res, err := RegexExtract(`abc(\d{2}).*(\w)`, "abc123999ok")
    13  	tt.Equal(true, err == nil)
    14  	tt.Equal([]string{"12", "k"}, res[1:])
    15  	res2, err := RegexExtractAll(`a(\d{2})`, "a123999oa23kdsfsda323")
    16  	tt.EqualExit(true, err == nil)
    17  	t.Log(res2)
    18  	tt.Equal(res2[0][1], "12")
    19  	tt.Equal(res2[1][1], "23")
    20  	tt.Equal(res2[2][1], "32")
    21  	res2, err = RegexExtractAll(`a(\d{2})`, "a123999oa23kdsfsda323", 1)
    22  	tt.EqualExit(true, err == nil)
    23  	t.Log(res2)
    24  	tt.Equal(res2[0][1], "12")
    25  }
    26  
    27  func TestRegex(T *testing.T) {
    28  	t := zlsgo.NewTest(T)
    29  	t.Equal(true, RegexMatch("是我啊", "这就是我啊!"))
    30  	t.Equal(false, RegexMatch("是你呀", "这就是我啊!"))
    31  
    32  	phone := "13800138000"
    33  	isPhone := RegexMatch(`^1[\d]{10}$`, phone)
    34  	t.Equal(true, isPhone)
    35  	phone = "1380013800x"
    36  	isPhone = RegexMatch(`^1[\d]{10}$`, phone)
    37  	t.Equal(false, isPhone)
    38  
    39  	t.Equal(2, len(RegexFind(`\d{2}`, "a1b23c456", -1)))
    40  	t.Equal(0, len(RegexFind(`\d{2}`, "abc", -1)))
    41  
    42  	str, _ := RegexReplace(`b\d{2}`, "a1b23c456", "*")
    43  	t.Equal("a1*c456", str)
    44  
    45  	strs, _ := RegexSplit(`~m~[0-9]{1,}~m~`, "~m~4~m~~h~1")
    46  	t.Equal([]string{"", "~h~1"}, strs)
    47  
    48  	str, _ = RegexReplaceFunc(`\w{2}`, "abcd", Ucfirst)
    49  	t.Equal("AbCd", str)
    50  
    51  	clearRegexpCompile()
    52  
    53  	regexCache = map[string]*regexMapStruct{}
    54  	clearRegexpCompile()
    55  }
    56  
    57  func BenchmarkRegex1(b *testing.B) {
    58  	for i := 0; i < b.N; i++ {
    59  		RegexMatch("是我啊", "这就是我啊!")
    60  	}
    61  }
    62  
    63  func BenchmarkRegex2(b *testing.B) {
    64  	for i := 0; i < b.N; i++ {
    65  		r, _ := regexp.Compile("是我啊")
    66  		r.Match(String2Bytes("这就是我啊!"))
    67  	}
    68  }
    69  
    70  func BenchmarkRegex3(b *testing.B) {
    71  	r, _ := regexp.Compile("是我啊")
    72  	for i := 0; i < b.N; i++ {
    73  		r.Match(String2Bytes("这就是我啊!"))
    74  	}
    75  }