Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

基本介绍

gregex提供了对正则表达式的支持,底层是对标准库regexp的封装,极大地简化了正则的使用,并采用了解析缓存设计,提高了执行效率。

  • 当函数名中有 All 的时候,它会继续查找非重叠的后续并返回 slice
  • 当函数名中有 String 的时候,参数及返回值都是 []string,否则为 []byte

    使用方式:

    Code Block
    languagego
    import "github.com/gogf/gf/v2/text/gregex"

    接口文档

    https://godocpkg.go.orgdev/github.com/gogf/gf/text/gregex

    简单示例:

    package main
    
    import (
        "fmt"
        "github.com/gogf/gf/text/gregex"
    )
    
    func main() {
        match, _ := gregex.MatchString(`(\w+).+\-\-\s*(.+)`, `GF is best! -- John`)
        fmt.Printf(`%s says "%s" is the one he loves!`, match[2], match[1])
    }
    

    执行后,输出结果为: 

    John says "GF" is the one he loves!

    IsMatch / IsMatchString

  • 说明: IsMatch()方法可以测试字符串,判断是否匹配正则表达式的模式。如果发现一次匹配,该方法返回"true",否则返回"false"。
  • 格式:

    Code Block
    IsMatch(pattern string, src []byte) bool
    IsMatchString(pattern string, src string) bool
  • Tip: regexp已经在底层处理并缓存了Regex对象,无需每次显式重新创建,下同。
  • 示例

    Code Block
    func ExampleIsMatch() {
    	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!")))
    
    	// Output:
    	// true
    	// false
    	// false
    }

    Match / MatchString

  • 说明:用来匹配子字符串,Match只返回第一个匹配的结果。区别于原生的正则方法,gregex是对FindSubmatch进行封装,直接返回第一个包括子模式结果的 slice
  • 格式

    Code Block
    Match(pattern string, src []byte) ([][]byte, error)
    MatchString(pattern string, src string) ([]string, error)
    示例:匹配 url 中的参数。
    Code Block
    func ExampleMatch() {
    	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.Match(patternStr, []byte(matchStr))
    	g.Dump(result)
    	g.Dump(err)
    
    	// Output:
    	// [
    	//     "pageId=1114219",
    	//     "pageId",
    	//     "1114219",
    	// ]
    	// <nil>
    }

    v2/text/gregex

    相关文档

    Children Display
    alltrue
    excerptTypesimple

    MatchAll / MatchAllString

    说明:用来匹配子字符串,MatchAll返回全部的结果。区别于原生的正则方法,gregex的 MatchAll 是对FindAllSubmatch方法进行封装,返回所有结果集的 slice,包括结果集中的子模式的结果。下面这个例子是匹配 url 中的参数。

    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)
    }

    执行后输出

    Code Block
    "\[1-9\]\\d\+"

    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

    说明:用来替换所有匹配的字符串,返回一个源字符串的拷贝。与replace 的区别在于,该方法可以在闭包中对查询进行二次判断或处理,而非简单的替换。

    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

    replaceFuncMatch返回src的拷贝,其中regexp的所有匹配都被应用于匹配字节切片的函数的返回值替换。 返回的替换直接替换。

    说明:用来替换所有匹配的字符串,返回一个源字符串的拷贝。该方法的强大之处在于可以在闭包中对查询进行二次判断或处理,且 matchString 函数包含了所有子模式的查询结果,而非简单的替换。

    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

    说明:将文本内容由指定的正则表达式进行切割。不包含元字符,相当于strings.SplitN。

    Code Block
    package main
    
    import (
        "fmt"
        "github.com/gogf/gf/text/gregex"
    )
    
    func main() {
        patternStr := `\d+`
    	str := "hello2020gf"
    	result := gregex.Split(patternStr, str)
    	g.Dump(result)
    }

    执行后输出

    Code Block
    ["hello","gf"]

    Validate

    说明:基于原生方法 compile 封装,检查给定的正则表达式是否有效

    Code Block
    package main
    
    import (
        "fmt"
        "github.com/gogf/gf/text/gregex"
    )
    
    func main() {
        // Valid match statement
    	g.Dump(gregex.Validate(`\d+`))
    	// Mismatched statement
    	g.Dump(gregex.Validate(`[a-9]\d+`))
    }

    执行后输出

    Code Block<nil> { Code: "invalid character class range", Expr: "a-9", }






    Panel
    titleContent Menu

    Table of Contents