Regular Expressions - Methods

Regular Expressions - Methods - 图1 tip

The following is a list of common methods. Documentation updates may lag behind new code features. For more methods and examples, please refer to the code documentation: https://pkg.go.dev/github.com/gogf/gf/v2/text/gregex

When the function name contains All, it will continue to search for non-overlapping follow-ups and return a slice.

When the function name contains String, the parameters and return values are string, otherwise they are []byte.

IsMatch/IsMatchString

  • Description: The IsMatch() method can test a string to determine whether it matches the pattern of a regular expression. If one match is found, the method returns true; otherwise, it returns false.
  • Format:
IsMatch(pattern string, src []byte) bool
IsMatchString(pattern string, src string) bool
  • Tip: regexp has already handled and cached the Regex object at the bottom level to significantly improve execution efficiency, so there is no need to explicitly recreate it each time.
  • Example:
func ExampleIsMatch() {
      patternStr := `\d+`
      g.Dump(gregex.IsMatch(patternStr, []byte("hello 2022! hello GoFrame!")))
      g.Dump(gregex.IsMatch(patternStr, nil))
      g.Dump(gregex.IsMatch(patternStr, []byte("hello GoFrame!")))

      // Output:
      // true
      // false
      // false
}

Match/MatchString

  • Description: Used to match substrings. Match only returns the first matching result. Unlike native regex methods, gregex wraps FindSubmatch to directly return a slice of the first sub-pattern result.
  • Format:
Match(pattern string, src []byte) ([][]byte, error)
MatchString(pattern string, src string) ([]string, error)
  • Example: Matching parameters in url.
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>
}

MatchAll/MatchAllString

  • Description: Used for matching substrings, MatchAll returns all results. Unlike native regex methods, gregex‘s MatchAll wraps FindAllSubmatch, returning a slice of all result sets, including sub-pattern results within the result sets.
  • Format:
MatchAllString(pattern string, src string) ([][]string, error)
MatchAll(pattern string, src []byte) ([][][]byte, error)
  • Example: The following example matches the parameters in url.
func ExampleMatchAll() {
      patternStr := `(\w+)=(\w+)`
      matchStr := "https://goframe.org/pages/viewpage.action?pageId=1114219&searchId=8QC5D1D2E!"
      result, err := gregex.MatchAll(patternStr, []byte(matchStr))
      g.Dump(result)
      g.Dump(err)

      // Output:
      //  [
      //     [
      //         "pageId=1114219",
      //         "pageId",
      //         "1114219",
      //     ],
      //     [
      //         "searchId=8QC5D1D2E",
      //         "searchId",
      //         "8QC5D1D2E",
      //     ],
      // ]
      // <nil>
}

func ExampleMatchAllString() {
      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)

      // Output:
      // [
      //     [
      //         "pageId=1114219",
      //         "pageId",
      //         "1114219",
      //     ],
      //     [
      //         "searchId=8QC5D1D2E",
      //         "searchId",
      //         "8QC5D1D2E",
      //     ],
      // ]
      // <nil>
}

Quote

  • Description: Escapes specific symbols in the given regular expression.
  • Format:
Quote(s string) string
  • Example:
func ExampleQuote() {
      result := gregex.Quote(`[1-9]\d+`)
      g.Dump(result)

      // Output:
      // "\[1-9\]\\d\+"
}

Replace/ReplaceString

  • Description: Used to replace all matching strings and return a copy of the source string.
  • Format:
Replace(pattern string, replace, src []byte) ([]byte, error)
ReplaceString(pattern, replace, src string) (string, error)
  • Example:
func ExampleReplace() {
      var (
          patternStr  = `\d+`
          str         = "hello GoFrame 2020!"
          repStr      = "2021"
          result, err = gregex.Replace(patternStr, []byte(repStr), []byte(str))
      )
      g.Dump(err)
      g.Dump(result)

      // Output:
      // <nil>
      // "hello GoFrame 2021!"
}

ReplaceFunc/ReplaceStringFunc

  • Description: Used to replace all matching strings and return a copy of the source string. Unlike the Replace method, this method allows secondary evaluation or processing within a closure instead of simple replacement.
  • Format:
ReplaceFunc(pattern string, src []byte, replaceFunc func(b []byte) []byte) ([]byte, error)
ReplaceStringFunc(pattern string, src string, replaceFunc func(s string) string) (string, error)
  • Example:
func ExampleReplaceFunc() {
      var (
          patternStr = `(\d+)~(\d+)`
          str        = "hello GoFrame 2018~2020!"
      )
      // In contrast to [ExampleReplace]
      result, err := gregex.ReplaceFunc(patternStr, []byte(str), func(match []byte) []byte {
          g.Dump(match)
          return bytes.Replace(match, []byte("2020"), []byte("2023"), -1)
      })
      g.Dump(result)
      g.Dump(err)

      // ReplaceStringFunc
      resultStr, _ := gregex.ReplaceStringFunc(patternStr, str, func(match string) string {
          g.Dump(match)
          return strings.Replace(match, "2020", "2023", -1)
      })
      g.Dump(resultStr)
      g.Dump(err)

         // Output:
      // "2018~2020"
      // "hello gf 2018~2023!" // ReplaceFunc result
      // <nil>
      // "2018~2020"
      // "hello gf 2018-2023!" // ReplaceStringFunc result
      // <nil>
}

ReplaceFuncMatch/ReplaceStringFuncMatch

ReplaceFuncMatch returns a copy of src, where all matches of regexp are replaced by the function‘s return value applied to the matched byte slices. The returned replacement replaces directly.

  • Description: Used to replace all matching strings and return a copy of the source string. The power of this method lies in secondary evaluation or processing within a closure, where the MatchString function contains all sub-pattern query results, rather than simple replacement.
  • Format:
ReplaceFuncMatch(pattern string, src []byte, replaceFunc func(match [][]byte) []byte) ([]byte, error)
ReplaceStringFuncMatch(pattern string, src string, replaceFunc func(match []string) string) (string, error)
  • Example:
func ExampleReplaceStringFuncMatch() {
       var (
          patternStr = `([A-Z])\w+`
          str        = "hello Golang 2018~2021!"
      )
      // In contrast to [ExampleReplaceFunc]
      // the result contains the `pattern' of all subpatterns that use the matching function
      result, err := gregex.ReplaceFuncMatch(patternStr, []byte(str), func(match [][]byte) []byte {
          g.Dump(match)
          return []byte("GoFrame")
      })
      g.Dump(result)
      g.Dump(err)

      // ReplaceStringFuncMatch
      resultStr, err := gregex.ReplaceStringFuncMatch(patternStr, str, func(match []string) string {
          g.Dump(match)
          match[0] = "Gf"
          return match[0]
      })
      g.Dump(resultStr)
      g.Dump(err)

      // Output:
      // [
      //     "Golang",
      //     "G",
      // ]
      // "hello GoFrame 2018~2021!" // ReplaceFuncMatch result
      // <nil>
      // [
      //     "Golang",
      //     "G",
      // ]
      // "hello Gf 2018~2021!" // ReplaceStringFuncMatch result
      // <nil>
}

Split

  • Description: Splits the text content using the specified regular expression. Without metacharacters, equivalent to strings.SplitN.
  • Format:
Split(pattern string, src string) []string
  • Example:
func ExampleSplit() {
      patternStr := `\d+`
      str := "hello2020GoFrame"
      result := gregex.Split(patternStr, str)
      g.Dump(result)

      // Output:
      // [
      //     "hello",
      //     "GoFrame",
      // ]
}

Validate

  • Description: Wraps the native compile method to check if the given regular expression is valid.
  • Format:
Validate(pattern string) error
  • Example:
func ExampleValidate() {
      // Valid match statement
      g.Dump(gregex.Validate(`\d+`))
      // Mismatched statement
      g.Dump(gregex.Validate(`[a-9]\d+`))

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