...
John says "GF" is the one he loves!
IsMatch / IsMatchString
Code Block |
---|
package main
import (
"fmt"
"github.com/gogf/gf/text/gregex"
)
func main() {
patternStr := `\d+`
g.Dump(gregex.IsMatch(patternStr, []byte("hello 2022! hello gf!")))
g.Dump(gregex.IsMatch(patternStr, nil))
g.Dump(gregex.IsMatch(patternStr, []byte("hello gf!")))
} |
执行后,输出结果为:
Code Block |
---|
true
false
false |
Match / MatchString
Code Block |
---|
package main
import (
"fmt"
"github.com/gogf/gf/text/gregex"
)
func main() {
patternStr := `(\w+)=(\w+)`
matchStr := "https://goframe.org/pages/viewpage.action?pageId=1114219&searchId=8QC5D1D2E!"
// This method looks for the first match index
result, err := gregex.MatchString(patternStr, matchStr)
g.Dump(result)
g.Dump(err)
} |
执行后,输出结果为
Code Block |
---|
[
"pageId=1114219",
"pageId",
"1114219",
]
<nil> |
MatchAll / MatchAllString
Code Block |
---|
package main
import (
"fmt"
"github.com/gogf/gf/text/gregex"
)
func main() {
patternStr := `(\w+)=(\w+)`
matchStr := "https://goframe.org/pages/viewpage.action?pageId=1114219&searchId=8QC5D1D2E!"
result, err := gregex.MatchAllString(patternStr, matchStr)
g.Dump(result)
g.Dump(err)
} |
执行代码后输出
Code Block |
---|
[
[
"pageId=1114219",
"pageId",
"1114219",
],
[
"searchId=8QC5D1D2E",
"searchId",
"8QC5D1D2E",
],
]
<nil> |
Quote
Code Block |
---|
package main
import (
"fmt"
"github.com/gogf/gf/text/gregex"
)
func main() {
result := gregex.Quote(`[1-9]\d+`)
g.Dump(result)
} |
执行后输出
Replace / ReplaceString
Code Block |
---|
package main
import (
"fmt"
"github.com/gogf/gf/text/gregex"
)
func main() {
var (
patternStr = `\d+`
str = "hello gf 2020!"
repStr = "2021"
result, err = gregex.Replace(patternStr, []byte(repStr), []byte(str))
)
g.Dump(err)
g.Dump(result)
} |
执行后输出
Code Block |
---|
<nil>
"hello gf 2021!" |
ReplaceFunc / ReplaceStringFunc
Code Block |
---|
package main
import (
"fmt"
"github.com/gogf/gf/text/gregex"
)
func main() {
replaceStrMap := map[string]string{
"2020": "2021",
}
// When the regular statement can match multiple results
// func can be used to further control the value that needs to be modified
result, err := gregex.ReplaceStringFunc(`\d+`, `hello gf 2018~2020!`, func(b string) string {
if replaceStr, ok := replaceStrMap[b]; ok {
return replaceStr
}
return b
})
g.Dump(result)
g.Dump(err)
result, err = gregex.ReplaceStringFunc(`[a-z]*`, "gf@goframe.org", strings.ToUpper)
g.Dump(result)
g.Dump(err)
} |
执行后输出
Code Block |
---|
"hello gf 2018~2021!"
<nil>
"GF@GOFRAME.ORG"
<nil> |
ReplaceFuncMatch / ReplaceStringFuncMatch
Code Block |
---|
package main
import (
"fmt"
"github.com/gogf/gf/text/gregex"
)
func main() {
var (
patternStr = `([A-Z])\w+`
str = "hello Golang 2018~2021!"
)
result, err := gregex.ReplaceStringFuncMatch(patternStr, str, func(match []string) string {
match[0] = "Gf"
return match[0]
})
g.Dump(result)
g.Dump(err)
} |
执行后输出
Code Block |
---|
"hello Gf 2018~2021!"
<nil> |
Split
Validate