This is a creation in Article, where the information may have evolved or changed.
Regular grammar google/Re2
Printf syntax
Several function methods
Name |
Description |
Note |
Match |
Verify that regular expressions match []byte |
- |
Matchstring |
Verify that the regular expression matches string |
- |
Findallstring |
The RegExp method, which matches the string, returns the matching result consisting of a []string. The qualification parameter-1 means no qualification, and the other indicates the qualification. |
- |
Findallstringsubmatch |
RegExp method, returns a [][]string |
- |
Example
Matchstring
func MatchString(pattern string, s string) (matched bool, err error)
matched, err := regexp.MatchString("foo.*", "seafood")fmt.Println(matched, err)matched, err = regexp.MatchString("bar.*", "seafood")fmt.Println(matched, err)matched, err = regexp.MatchString("a(b", "seafood")fmt.Println(matched, err)/*output:true <nil>false <nil>false error parsing regexp: missing closing ): `a(b`*/
Findallstring
func (re *Regexp) FindAllString(s string, n int) []string
re := regexp.MustCompile("a.")fmt.Println(re.FindAllString("paranormal", -1))fmt.Println(re.FindAllString("paranormal", 2))fmt.Println(re.FindAllString("graal", -1))fmt.Println(re.FindAllString("none", -1))/*output:[ar an al][ar an][aa][]*/
Findallstringsubmatch
func (re *Regexp) FindAllStringSubmatch(s string, n int) [][]string
re := regexp.MustCompile("a(x*)b")fmt.Printf("%q\n", re.FindAllStringSubmatch("-ab-", -1))fmt.Printf("%q\n", re.FindAllStringSubmatch("-axxb-", -1))fmt.Printf("%q\n", re.FindAllStringSubmatch("-ab-axb-", -1))fmt.Printf("%q\n", re.FindAllStringSubmatch("-axxb-ab-", -1))/*output:[["ab" ""]][["axxb" "xx"]][["ab" ""] ["axb" "x"]][["axxb" "xx"] ["ab" ""]]*/
FindString
func (re *Regexp) FindString(s string) string
re := regexp.MustCompile("fo.?")fmt.Printf("%q\n", re.FindString("seafood"))fmt.Printf("%q\n", re.FindString("meat"))/*output:"foo"""*/
Findstringsubmatch
func (re *Regexp) FindStringSubmatch(s string) []string
re := regexp.MustCompile("a(x*)b(y|z)c")fmt.Printf("%q\n", re.FindStringSubmatch("-axxxbyc-"))fmt.Printf("%q\n", re.FindStringSubmatch("-abzc-"))/*output:["axxxbyc" "xxx" "y"]["abzc" "" "z"]*/
Note:
1) Here the%q, which represents the double quotation mark display.
2) The difference between Findallstringsubmatch and Findstringsubmatch
re := regexp.MustCompile("a(x*)b")fmt.Printf("%q\n", re.FindAllStringSubmatch("-ab-axb-", -1))fmt.Printf("%q\n", re.FindStringSubmatch("-ab-axb-"))/*output:[["ab" ""] ["axb" "x"]]["ab" ""]*/