regexp
Index
- func Match(pattern string, b []byte) (matched bool, err error)
- func MatchReader(pattern string, r io.RuneReader) (matched bool, err error)
- func MatchString(pattern string, s string) (matched bool, err error)
- func QuoteMeta(s string) string
- func Compile(expr string) (*Regexp, error)
- func CompilePOSIX(expr string) (*Regexp, error)
- func MustCompile(str string) *Regexp
- func MustCompilePOSIX(str string) *Regexp
- type Regexp
- func Compile(expr string) (*Regexp, error)
- func CompilePOSIX(expr string) (*Regexp, error)
- func MustCompile(str string) *Regexp
- func MustCompilePOSIX(str string) *Regexp
- func (re *Regexp) Copy() *Regexp
- func (re *Regexp) Expand(dst []byte, template []byte, src []byte, match []int) []byte
- func (re *Regexp) ExpandString(dst []byte, template string, src string, match []int) []byte
- func (re *Regexp) Find(b []byte) []byte
- func (re *Regexp) FindAll(b []byte, n int) [][]byte
- func (re *Regexp) FindAllIndex(b []byte, n int) [][]int
- func (re *Regexp) FindAllString(s string, n int) []string
- func (re *Regexp) FindAllStringIndex(s string, n int) [][]int
- func (re *Regexp) FindAllStringSubmatch(s string, n int) [][]string
- func (re *Regexp) FindAllStringSubmatchIndex(s string, n int) [][]int
- func (re *Regexp) FindAllSubmatch(b []byte, n int) [][][]byte
- func (re *Regexp) FindAllSubmatchIndex(b []byte, n int) [][]int
- func (re *Regexp) FindIndex(b []byte) (loc []int)
- func (re *Regexp) FindReaderIndex(r io.RuneReader) (loc []int)
- func (re *Regexp) FindReaderSubmatchIndex(r io.RuneReader) []int
- func (re *Regexp) FindString(s string) string
- func (re *Regexp) FindStringIndex(s string) (loc []int)
- func (re *Regexp) FindStringSubmatch(s string) []string
- func (re *Regexp) FindStringSubmatchIndex(s string) []int
- func (re *Regexp) FindSubmatch(b []byte) [][]byte
- func (re *Regexp) FindSubmatchIndex(b []byte) []int
- func (re *Regexp) LiteralPrefix() (prefix string, complete bool)
- func (re *Regexp) Longest()
- func (re *Regexp) MarshalText() ([]byte, error)
- func (re *Regexp) Match(b []byte) bool
- func (re *Regexp) MatchReader(r io.RuneReader) bool
- func (re *Regexp) MatchString(s string) bool
- func (re *Regexp) NumSubexp() int
- func (re *Regexp) ReplaceAll(src, repl []byte) []byte
- func (re *Regexp) ReplaceAllFunc(src []byte, repl func([]byte) []byte) []byte
- func (re *Regexp) ReplaceAllLiteral(src, repl []byte) []byte
- func (re *Regexp) ReplaceAllLiteralString(src, repl string) string
- func (re *Regexp) ReplaceAllString(src, repl string) string
- func (re *Regexp) ReplaceAllStringFunc(src string, repl func(string) string) string
- func (re *Regexp) Split(s string, n int) []string
- func (re *Regexp) String() string
- func (re *Regexp) SubexpIndex(name string) int
- func (re *Regexp) SubexpNames() []string
- func (re *Regexp) UnmarshalText(text []byte) error
Functions
func Match
1func Match(pattern string, b []byte) (matched bool, err error)Match reports whether the byte slice b contains any match of the regular expression pattern. More complicated queries need to use Compile and the full Regexp interface.
1matched, err := regexp.Match(`foo.*`, []byte(`seafood`))
2fmt.Println(matched, err)
3matched, err = regexp.Match(`bar.*`, []byte(`seafood`))
4fmt.Println(matched, err)
5matched, err = regexp.Match(`a(b`, []byte(`seafood`))
6fmt.Println(matched, err)Output
truefalse false error parsing regexp: missing closing ): `a(b`
func MatchReader
1func MatchReader(pattern string, r io.RuneReader) (matched bool, err error)MatchReader reports whether the text returned by the io.RuneReader contains any match of the regular expression pattern. More complicated queries need to use Compile and the full Regexp interface.
func MatchString
1func MatchString(pattern string, s string) (matched bool, err error)MatchString reports whether the string s contains any match of the regular expression pattern. More complicated queries need to use Compile and the full Regexp interface.
1matched, err := regexp.MatchString(`foo.*`, "seafood")
2fmt.Println(matched, err)
3matched, err = regexp.MatchString(`bar.*`, "seafood")
4fmt.Println(matched, err)
5matched, err = regexp.MatchString(`a(b`, "seafood")
6fmt.Println(matched, err)Output
truefalse false error parsing regexp: missing closing ): `a(b`
func QuoteMeta
1func QuoteMeta(s string) stringQuoteMeta returns a string that escapes all regular expression metacharacters inside the argument text; the returned string is a regular expression matching the literal text.
1fmt.Println(regexp.QuoteMeta(`Escaping symbols like: .+*?()|[]{}^$`))Output
Escaping symbols like: \.\+\*\?\(\)\|\[\]\{\}\^\$
func Compile
1func Compile(expr string) (*Regexp, error)Compile parses a regular expression and returns, if successful, a Regexp object that can be used to match against text.
When matching against text, the regexp returns a match that begins as early as possible in the input (leftmost), and among those it chooses the one that a backtracking search would have found first. This so-called leftmost-first matching is the same semantics that Perl, Python, and other implementations use, although this package implements it without the expense of backtracking. For POSIX leftmost-longest matching, see CompilePOSIX.
func CompilePOSIX
1func CompilePOSIX(expr string) (*Regexp, error)CompilePOSIX is like Compile but restricts the regular expression to POSIX ERE (egrep) syntax and changes the match semantics to leftmost-longest.
That is, when matching against text, the regexp returns a match that begins as early as possible in the input (leftmost), and among those it chooses a match that is as long as possible. This so-called leftmost-longest matching is the same semantics that early regular expression implementations used and that POSIX specifies.
However, there can be multiple leftmost-longest matches, with different submatch choices, and here this package diverges from POSIX. Among the possible leftmost-longest matches, this package chooses the one that a backtracking search would have found first, while POSIX specifies that the match be chosen to maximize the length of the first subexpression, then the second, and so on from left to right. The POSIX rule is computationally prohibitive and not even well-defined. See https://swtch.com/~rsc/regexp/regexp2.html#posix for details.
func MustCompile
1func MustCompile(str string) *RegexpMustCompile is like Compile but panics if the expression cannot be parsed. It simplifies safe initialization of global variables holding compiled regular expressions.
func MustCompilePOSIX
1func MustCompilePOSIX(str string) *RegexpMustCompilePOSIX is like CompilePOSIX but panics if the expression cannot be parsed. It simplifies safe initialization of global variables holding compiled regular expressions.
Types
type Regexp
1type Regexp struct {
2}Regexp is the representation of a compiled regular expression. A Regexp is safe for concurrent use by multiple goroutines, except for configuration methods, such as Regexp.Longest.
func Copy
1func (re *Regexp) Copy() *RegexpCopy returns a new Regexp object copied from re. Calling Regexp.Longest on one copy does not affect another.
Deprecated: In earlier releases, when using a Regexp in multiple goroutines, giving each goroutine its own copy helped to avoid lock contention. As of Go 1.12, using Copy is no longer necessary to avoid lock contention. Copy may still be appropriate if the reason for its use is to make two copies with different Regexp.Longest settings.
func Expand
1func (re *Regexp) Expand(dst []byte, template []byte, src []byte, match []int) []byteExpand appends template to dst and returns the result; during the append, Expand replaces variables in the template with corresponding matches drawn from src. The match slice should have been returned by Regexp.FindSubmatchIndex.
In the template, a variable is denoted by a substring of the form $name or
${name}, where name is a non-empty sequence of letters, digits, and underscores.
A purely numeric name like $1 refers to the submatch with the corresponding
index; other names refer to capturing parentheses named with the (?P
In the $name form, name is taken to be as long as possible: $1x is equivalent to ${1x}, not ${1}x, and, $10 is equivalent to ${10}, not ${1}0.
To insert a literal $ in the output, use $$ in the template.
1content := []byte(`
2# comment line
3option1: value1
4option2: value2
5
6# another comment line
7option3: value3
8`)
9
10pattern := regexp.MustCompile(`(?m)(?P<key>\w+):\s+(?P<value>\w+)$`)
11
12template := []byte("$key=$value\n")
13
14result := []byte{}
15
16for _, submatches := range pattern.FindAllSubmatchIndex(content, -1) {
17
18 result = pattern.Expand(result, template, content, submatches)
19}
20fmt.Println(string(result))Output
option1=value1 option2=value2 option3=value3
func ExpandString
1func (re *Regexp) ExpandString(dst []byte, template string, src string, match []int) []byteExpandString is like Regexp.Expand but the template and source are strings. It appends to and returns a byte slice in order to give the calling code control over allocation.
1content := `
2# comment line
3option1: value1
4option2: value2
5
6# another comment line
7option3: value3
8`
9
10pattern := regexp.MustCompile(`(?m)(?P<key>\w+):\s+(?P<value>\w+)$`)
11
12template := "$key=$value\n"
13
14result := []byte{}
15
16for _, submatches := range pattern.FindAllStringSubmatchIndex(content, -1) {
17
18 result = pattern.ExpandString(result, template, content, submatches)
19}
20fmt.Println(string(result))Output
option1=value1 option2=value2 option3=value3
func Find
1func (re *Regexp) Find(b []byte) []byteFind returns a slice holding the text of the leftmost match in b of the regular expression. A return value of nil indicates no match.
1re := regexp.MustCompile(`foo.?`)
2fmt.Printf("%q\n", re.Find([]byte(`seafood fool`)))Output
"food"
func FindAll
1func (re *Regexp) FindAll(b []byte, n int) [][]byteFindAll is the 'All' version of Regexp.Find; it returns a slice of all successive matches of the expression, as defined by the 'All' description in the package comment. A return value of nil indicates no match.
1re := regexp.MustCompile(`foo.?`)
2fmt.Printf("%q\n", re.FindAll([]byte(`seafood fool`), -1))Output
["food" "fool"]
func FindAllIndex
1func (re *Regexp) FindAllIndex(b []byte, n int) [][]intFindAllIndex is the 'All' version of Regexp.FindIndex; it returns a slice of all successive matches of the expression, as defined by the 'All' description in the package comment. A return value of nil indicates no match.
1content := []byte("London")
2re := regexp.MustCompile(`o.`)
3fmt.Println(re.FindAllIndex(content, 1))
4fmt.Println(re.FindAllIndex(content, -1))Output
[[1 3]] [[1 3] [4 6]]
func FindAllString
1func (re *Regexp) FindAllString(s string, n int) []stringFindAllString is the 'All' version of Regexp.FindString; it returns a slice of all successive matches of the expression, as defined by the 'All' description in the package comment. A return value of nil indicates no match.
1re := regexp.MustCompile(`a.`)
2fmt.Println(re.FindAllString("paranormal", -1))
3fmt.Println(re.FindAllString("paranormal", 2))
4fmt.Println(re.FindAllString("graal", -1))
5fmt.Println(re.FindAllString("none", -1))Output
[ar an al] [ar an] [aa] []
func FindAllStringIndex
1func (re *Regexp) FindAllStringIndex(s string, n int) [][]intFindAllStringIndex is the 'All' version of Regexp.FindStringIndex; it returns a slice of all successive matches of the expression, as defined by the 'All' description in the package comment. A return value of nil indicates no match.
func FindAllStringSubmatch
1func (re *Regexp) FindAllStringSubmatch(s string, n int) [][]stringFindAllStringSubmatch is the 'All' version of Regexp.FindStringSubmatch; it returns a slice of all successive matches of the expression, as defined by the 'All' description in the package comment. A return value of nil indicates no match.
1re := regexp.MustCompile(`a(x*)b`)
2fmt.Printf("%q\n", re.FindAllStringSubmatch("-ab-", -1))
3fmt.Printf("%q\n", re.FindAllStringSubmatch("-axxb-", -1))
4fmt.Printf("%q\n", re.FindAllStringSubmatch("-ab-axb-", -1))
5fmt.Printf("%q\n", re.FindAllStringSubmatch("-axxb-ab-", -1))Output
[["ab" ""]] [["axxb" "xx"]] [["ab" ""] ["axb" "x"]] [["axxb" "xx"] ["ab" ""]]
func FindAllStringSubmatchIndex
1func (re *Regexp) FindAllStringSubmatchIndex(s string, n int) [][]intFindAllStringSubmatchIndex is the 'All' version of Regexp.FindStringSubmatchIndex; it returns a slice of all successive matches of the expression, as defined by the 'All' description in the package comment. A return value of nil indicates no match.
1re := regexp.MustCompile(`a(x*)b`)
2
3fmt.Println(re.FindAllStringSubmatchIndex("-ab-", -1))
4fmt.Println(re.FindAllStringSubmatchIndex("-axxb-", -1))
5fmt.Println(re.FindAllStringSubmatchIndex("-ab-axb-", -1))
6fmt.Println(re.FindAllStringSubmatchIndex("-axxb-ab-", -1))
7fmt.Println(re.FindAllStringSubmatchIndex("-foo-", -1))Output
[[1 3 2 2]] [[1 5 2 4]] [[1 3 2 2] [4 7 5 6]] [[1 5 2 4] [6 8 7 7]] []
func FindAllSubmatch
1func (re *Regexp) FindAllSubmatch(b []byte, n int) [][][]byteFindAllSubmatch is the 'All' version of Regexp.FindSubmatch; it returns a slice of all successive matches of the expression, as defined by the 'All' description in the package comment. A return value of nil indicates no match.
1re := regexp.MustCompile(`foo(.?)`)
2fmt.Printf("%q\n", re.FindAllSubmatch([]byte(`seafood fool`), -1))Output
[["food" "d"] ["fool" "l"]]
func FindAllSubmatchIndex
1func (re *Regexp) FindAllSubmatchIndex(b []byte, n int) [][]intFindAllSubmatchIndex is the 'All' version of Regexp.FindSubmatchIndex; it returns a slice of all successive matches of the expression, as defined by the 'All' description in the package comment. A return value of nil indicates no match.
1content := []byte(`
2# comment line
3option1: value1
4option2: value2
5`)
6
7pattern := regexp.MustCompile(`(?m)(?P<key>\w+):\s+(?P<value>\w+)$`)
8allIndexes := pattern.FindAllSubmatchIndex(content, -1)
9for _, loc := range allIndexes {
10 fmt.Println(loc)
11 fmt.Println(string(content[loc[0]:loc[1]]))
12 fmt.Println(string(content[loc[2]:loc[3]]))
13 fmt.Println(string(content[loc[4]:loc[5]]))
14}Output
[18 33 18 25 27 33] option1: value1 option1 value1 [35 50 35 42 44 50] option2: value2 option2 value2
func FindIndex
1func (re *Regexp) FindIndex(b []byte) (loc []int)FindIndex returns a two-element slice of integers defining the location of the leftmost match in b of the regular expression. The match itself is at b[loc[0]:loc[1]]. A return value of nil indicates no match.
1content := []byte(`
2# comment line
3option1: value1
4option2: value2
5`)
6
7pattern := regexp.MustCompile(`(?m)(?P<key>\w+):\s+(?P<value>\w+)$`)
8
9loc := pattern.FindIndex(content)
10fmt.Println(loc)
11fmt.Println(string(content[loc[0]:loc[1]]))Output
[18 33] option1: value1
func FindReaderIndex
1func (re *Regexp) FindReaderIndex(r io.RuneReader) (loc []int)FindReaderIndex returns a two-element slice of integers defining the location of the leftmost match of the regular expression in text read from the io.RuneReader. The match text was found in the input stream at byte offset loc[0] through loc[1]-1. A return value of nil indicates no match.
func FindReaderSubmatchIndex
1func (re *Regexp) FindReaderSubmatchIndex(r io.RuneReader) []intFindReaderSubmatchIndex returns a slice holding the index pairs identifying the leftmost match of the regular expression of text read by the io.RuneReader, and the matches, if any, of its subexpressions, as defined by the 'Submatch' and 'Index' descriptions in the package comment. A return value of nil indicates no match.
func FindString
1func (re *Regexp) FindString(s string) stringFindString returns a string holding the text of the leftmost match in s of the regular expression. If there is no match, the return value is an empty string, but it will also be empty if the regular expression successfully matches an empty string. Use Regexp.FindStringIndex or Regexp.FindStringSubmatch if it is necessary to distinguish these cases.
1re := regexp.MustCompile(`foo.?`)
2fmt.Printf("%q\n", re.FindString("seafood fool"))
3fmt.Printf("%q\n", re.FindString("meat"))Output
"food" ""
func FindStringIndex
1func (re *Regexp) FindStringIndex(s string) (loc []int)FindStringIndex returns a two-element slice of integers defining the location of the leftmost match in s of the regular expression. The match itself is at s[loc[0]:loc[1]]. A return value of nil indicates no match.
1re := regexp.MustCompile(`ab?`)
2fmt.Println(re.FindStringIndex("tablett"))
3fmt.Println(re.FindStringIndex("foo") == nil)Output
[1 3] true
func FindStringSubmatch
1func (re *Regexp) FindStringSubmatch(s string) []stringFindStringSubmatch returns a slice of strings holding the text of the leftmost match of the regular expression in s and the matches, if any, of its subexpressions, as defined by the 'Submatch' description in the package comment. A return value of nil indicates no match.
1re := regexp.MustCompile(`a(x*)b(y|z)c`)
2fmt.Printf("%q\n", re.FindStringSubmatch("-axxxbyc-"))
3fmt.Printf("%q\n", re.FindStringSubmatch("-abzc-"))Output
["axxxbyc" "xxx" "y"] ["abzc" "" "z"]
func FindStringSubmatchIndex
1func (re *Regexp) FindStringSubmatchIndex(s string) []intFindStringSubmatchIndex returns a slice holding the index pairs identifying the leftmost match of the regular expression in s and the matches, if any, of its subexpressions, as defined by the 'Submatch' and 'Index' descriptions in the package comment. A return value of nil indicates no match.
func FindSubmatch
1func (re *Regexp) FindSubmatch(b []byte) [][]byteFindSubmatch returns a slice of slices holding the text of the leftmost match of the regular expression in b and the matches, if any, of its subexpressions, as defined by the 'Submatch' descriptions in the package comment. A return value of nil indicates no match.
1re := regexp.MustCompile(`foo(.?)`)
2fmt.Printf("%q\n", re.FindSubmatch([]byte(`seafood fool`)))Output
["food" "d"]
func FindSubmatchIndex
1func (re *Regexp) FindSubmatchIndex(b []byte) []intFindSubmatchIndex returns a slice holding the index pairs identifying the leftmost match of the regular expression in b and the matches, if any, of its subexpressions, as defined by the 'Submatch' and 'Index' descriptions in the package comment. A return value of nil indicates no match.
1re := regexp.MustCompile(`a(x*)b`)
2
3fmt.Println(re.FindSubmatchIndex([]byte("-ab-")))
4fmt.Println(re.FindSubmatchIndex([]byte("-axxb-")))
5fmt.Println(re.FindSubmatchIndex([]byte("-ab-axb-")))
6fmt.Println(re.FindSubmatchIndex([]byte("-axxb-ab-")))
7fmt.Println(re.FindSubmatchIndex([]byte("-foo-")))Output
[1 3 2 2] [1 5 2 4] [1 3 2 2] [1 5 2 4] []
func LiteralPrefix
1func (re *Regexp) LiteralPrefix() (prefix string, complete bool)LiteralPrefix returns a literal string that must begin any match of the regular expression re. It returns the boolean true if the literal string comprises the entire regular expression.
func Longest
1func (re *Regexp) Longest()Longest makes future searches prefer the leftmost-longest match. That is, when matching against text, the regexp returns a match that begins as early as possible in the input (leftmost), and among those it chooses a match that is as long as possible. This method modifies the Regexp and may not be called concurrently with any other methods.
1re := regexp.MustCompile(`a(|b)`)
2fmt.Println(re.FindString("ab"))
3re.Longest()
4fmt.Println(re.FindString("ab"))Output
a ab
func MarshalText
1func (re *Regexp) MarshalText() ([]byte, error)MarshalText implements encoding.TextMarshaler. The output matches that of calling the Regexp.String method.
Note that the output is lossy in some cases: This method does not indicate POSIX regular expressions (i.e. those compiled by calling CompilePOSIX), or those for which the Regexp.Longest method has been called.
func Match
1func (re *Regexp) Match(b []byte) boolMatch reports whether the byte slice b contains any match of the regular expression re.
1re := regexp.MustCompile(`foo.?`)
2fmt.Println(re.Match([]byte(`seafood fool`)))
3fmt.Println(re.Match([]byte(`something else`)))Output
true false
func MatchReader
1func (re *Regexp) MatchReader(r io.RuneReader) boolMatchReader reports whether the text returned by the io.RuneReader contains any match of the regular expression re.
func MatchString
1func (re *Regexp) MatchString(s string) boolMatchString reports whether the string s contains any match of the regular expression re.
1re := regexp.MustCompile(`(gopher){2}`)
2fmt.Println(re.MatchString("gopher"))
3fmt.Println(re.MatchString("gophergopher"))
4fmt.Println(re.MatchString("gophergophergopher"))Output
false true true
func NumSubexp
1func (re *Regexp) NumSubexp() intNumSubexp returns the number of parenthesized subexpressions in this Regexp.
1re0 := regexp.MustCompile(`a.`)
2fmt.Printf("%d\n", re0.NumSubexp())
3
4re := regexp.MustCompile(`(.*)((a)b)(.*)a`)
5fmt.Println(re.NumSubexp())Output
0 4
func ReplaceAll
1func (re *Regexp) ReplaceAll(src, repl []byte) []byteReplaceAll returns a copy of src, replacing matches of the Regexp with the replacement text repl. Inside repl, $ signs are interpreted as in Regexp.Expand.
1re := regexp.MustCompile(`a(x*)b`)
2fmt.Printf("%s\n", re.ReplaceAll([]byte("-ab-axxb-"), []byte("T")))
3fmt.Printf("%s\n", re.ReplaceAll([]byte("-ab-axxb-"), []byte("$1")))
4fmt.Printf("%s\n", re.ReplaceAll([]byte("-ab-axxb-"), []byte("$1W")))
5fmt.Printf("%s\n", re.ReplaceAll([]byte("-ab-axxb-"), []byte("${1}W")))
6
7re2 := regexp.MustCompile(`a(?P<1W>x*)b`)
8fmt.Printf("%s\n", re2.ReplaceAll([]byte("-ab-axxb-"), []byte("$1W")))
9fmt.Printf("%s\n", re2.ReplaceAll([]byte("-ab-axxb-"), []byte("${1}W")))Output
-T-T- --xx- --- -W-xxW- --xx- -W-xxW-
func ReplaceAllFunc
1func (re *Regexp) ReplaceAllFunc(src []byte, repl func([]byte) []byte) []byteReplaceAllFunc returns a copy of src in which all matches of the Regexp have been replaced by the return value of function repl applied to the matched byte slice. The replacement returned by repl is substituted directly, without using Regexp.Expand.
func ReplaceAllLiteral
1func (re *Regexp) ReplaceAllLiteral(src, repl []byte) []byteReplaceAllLiteral returns a copy of src, replacing matches of the Regexp with the replacement bytes repl. The replacement repl is substituted directly, without using Regexp.Expand.
func ReplaceAllLiteralString
1func (re *Regexp) ReplaceAllLiteralString(src, repl string) stringReplaceAllLiteralString returns a copy of src, replacing matches of the Regexp with the replacement string repl. The replacement repl is substituted directly, without using Regexp.Expand.
1re := regexp.MustCompile(`a(x*)b`)
2fmt.Println(re.ReplaceAllLiteralString("-ab-axxb-", "T"))
3fmt.Println(re.ReplaceAllLiteralString("-ab-axxb-", "$1"))
4fmt.Println(re.ReplaceAllLiteralString("-ab-axxb-", "${1}"))Output
-T-T-
-$1-$1-
-${1}-${1}-
func ReplaceAllString
1func (re *Regexp) ReplaceAllString(src, repl string) stringReplaceAllString returns a copy of src, replacing matches of the Regexp with the replacement string repl. Inside repl, $ signs are interpreted as in Regexp.Expand.
1re := regexp.MustCompile(`a(x*)b`)
2fmt.Println(re.ReplaceAllString("-ab-axxb-", "T"))
3fmt.Println(re.ReplaceAllString("-ab-axxb-", "$1"))
4fmt.Println(re.ReplaceAllString("-ab-axxb-", "$1W"))
5fmt.Println(re.ReplaceAllString("-ab-axxb-", "${1}W"))
6
7re2 := regexp.MustCompile(`a(?P<1W>x*)b`)
8fmt.Printf("%s\n", re2.ReplaceAllString("-ab-axxb-", "$1W"))
9fmt.Println(re.ReplaceAllString("-ab-axxb-", "${1}W"))Output
-T-T- --xx- --- -W-xxW- --xx- -W-xxW-
func ReplaceAllStringFunc
1func (re *Regexp) ReplaceAllStringFunc(src string, repl func(string) string) stringReplaceAllStringFunc returns a copy of src in which all matches of the Regexp have been replaced by the return value of function repl applied to the matched substring. The replacement returned by repl is substituted directly, without using Regexp.Expand.
1re := regexp.MustCompile(`[^aeiou]`)
2fmt.Println(re.ReplaceAllStringFunc("seafood fool", strings.ToUpper))Output
SeaFooD FooL
func Split
1func (re *Regexp) Split(s string, n int) []stringSplit slices s into substrings separated by the expression and returns a slice of the substrings between those expression matches.
The slice returned by this method consists of all the substrings of s not contained in the slice returned by Regexp.FindAllString. When called on an expression that contains no metacharacters, it is equivalent to strings.SplitN.
Example:
s := regexp.MustCompile("a*").Split("abaabaccadaaae", 5)
// s: ["", "b", "b", "c", "cadaaae"]
The count determines the number of substrings to return:
- n > 0: at most n substrings; the last substring will be the unsplit remainder;
- n == 0: the result is nil (zero substrings);
- n < 0: all substrings.
1a := regexp.MustCompile(`a`)
2fmt.Println(a.Split("banana", -1))
3fmt.Println(a.Split("banana", 0))
4fmt.Println(a.Split("banana", 1))
5fmt.Println(a.Split("banana", 2))
6zp := regexp.MustCompile(`z+`)
7fmt.Println(zp.Split("pizza", -1))
8fmt.Println(zp.Split("pizza", 0))
9fmt.Println(zp.Split("pizza", 1))
10fmt.Println(zp.Split("pizza", 2))Output
[b n n ] [] [banana] [b nana] [pi a] [] [pizza] [pi a]
func String
1func (re *Regexp) String() stringString returns the source text used to compile the regular expression.
func SubexpIndex
1func (re *Regexp) SubexpIndex(name string) intSubexpIndex returns the index of the first subexpression with the given name, or -1 if there is no subexpression with that name.
Note that multiple subexpressions can be written using the same name,
as in (?P
1re := regexp.MustCompile(`(?P<first>[a-zA-Z]+) (?P<last>[a-zA-Z]+)`)
2fmt.Println(re.MatchString("Alan Turing"))
3matches := re.FindStringSubmatch("Alan Turing")
4lastIndex := re.SubexpIndex("last")
5fmt.Printf("last => %d\n", lastIndex)
6fmt.Println(matches[lastIndex])Output
true last => 2 Turing
func SubexpNames
1func (re *Regexp) SubexpNames() []stringSubexpNames returns the names of the parenthesized subexpressions in this Regexp. The name for the first sub-expression is names[1], so that if m is a match slice, the name for m[i] is SubexpNames()[i]. Since the Regexp as a whole cannot be named, names[0] is always the empty string. The slice should not be modified.
1re := regexp.MustCompile(`(?P<first>[a-zA-Z]+) (?P<last>[a-zA-Z]+)`)
2fmt.Println(re.MatchString("Alan Turing"))
3fmt.Printf("%q\n", re.SubexpNames())
4reversed := fmt.Sprintf("${%s} ${%s}", re.SubexpNames()[2], re.SubexpNames()[1])
5fmt.Println(reversed)
6fmt.Println(re.ReplaceAllString("Alan Turing", reversed))Output
true
["" "first" "last"]
${last} ${first}
Turing Alan
func UnmarshalText
1func (re *Regexp) UnmarshalText(text []byte) errorUnmarshalText implements encoding.TextUnmarshaler by calling Compile on the encoded value.