regexp
packagestandard libraryThis package is not in the latest version of its module.
Details
Validgo.mod file
The Go module system was introduced in Go 1.11 and is the official dependency management solution for Go.
Redistributable license
Redistributable licenses place minimal restrictions on how software can be used, modified, and redistributed.
Tagged version
Modules with tagged versions give importers more predictable builds.
Stable version
When a project reaches major version v1 it is considered stable.
- Learn more about best practices
Repository
Links
Documentation¶
Overview¶
Package regexp implements regular expression search.
The syntax of the regular expressions accepted is the samegeneral syntax used by Perl, Python, and other languages.More precisely, it is the syntax accepted by RE2 and described athttps://golang.org/s/re2syntax, except for \C.For an overview of the syntax, see theregexp/syntax package.
The regexp implementation provided by this package isguaranteed to run in time linear in the size of the input.(This is a property not guaranteed by most open sourceimplementations of regular expressions.) For more informationabout this property, seehttps://swtch.com/~rsc/regexp/regexp1.htmlor any book about automata theory.
All characters are UTF-8-encoded code points.Followingutf8.DecodeRune, each byte of an invalid UTF-8 sequenceis treated as if it encoded utf8.RuneError (U+FFFD).
There are 16 methods ofRegexp that match a regular expression and identifythe matched text. Their names are matched by this regular expression:
Find(All)?(String)?(Submatch)?(Index)?
If 'All' is present, the routine matches successive non-overlappingmatches of the entire expression. Empty matches abutting a precedingmatch are ignored. The return value is a slice containing the successivereturn values of the corresponding non-'All' routine. These routines takean extra integer argument, n. If n >= 0, the function returns at most nmatches/submatches; otherwise, it returns all of them.
If 'String' is present, the argument is a string; otherwise it is a sliceof bytes; return values are adjusted as appropriate.
If 'Submatch' is present, the return value is a slice identifying thesuccessive submatches of the expression. Submatches are matches ofparenthesized subexpressions (also known as capturing groups) within theregular expression, numbered from left to right in order of openingparenthesis. Submatch 0 is the match of the entire expression, submatch 1 isthe match of the first parenthesized subexpression, and so on.
If 'Index' is present, matches and submatches are identified by byte indexpairs within the input string: result[2*n:2*n+2] identifies the indexes ofthe nth submatch. The pair for n==0 identifies the match of the entireexpression. If 'Index' is not present, the match is identified by the textof the match/submatch. If an index is negative or text is nil, it means thatsubexpression did not match any string in the input. For 'String' versionsan empty string means either no match or an empty match.
There is also a subset of the methods that can be applied to text read fromanio.RuneReader:Regexp.MatchReader,Regexp.FindReaderIndex,Regexp.FindReaderSubmatchIndex.
This set may grow. Note that regular expression matches may need toexamine text beyond the text returned by a match, so the methods thatmatch text from anio.RuneReader may read arbitrarily far into the inputbefore returning.
(There are a few other methods that do not match this pattern.)
Example¶
package mainimport ("fmt""regexp")func main() {// Compile the expression once, usually at init time.// Use raw strings to avoid having to quote the backslashes.var validID = regexp.MustCompile(`^[a-z]+\[[0-9]+\]$`)fmt.Println(validID.MatchString("adam[23]"))fmt.Println(validID.MatchString("eve[7]"))fmt.Println(validID.MatchString("Job[48]"))fmt.Println(validID.MatchString("snakey"))}Output:truetruefalsefalse
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
- type Regexp
- func (re *Regexp) AppendText(b []byte) ([]byte, error)
- func (re *Regexp) Copy() *Regexpdeprecated
- 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
Examples¶
- Package
- Match
- MatchString
- QuoteMeta
- Regexp.Expand
- Regexp.ExpandString
- Regexp.Find
- Regexp.FindAll
- Regexp.FindAllIndex
- Regexp.FindAllString
- Regexp.FindAllStringSubmatch
- Regexp.FindAllStringSubmatchIndex
- Regexp.FindAllSubmatch
- Regexp.FindAllSubmatchIndex
- Regexp.FindIndex
- Regexp.FindString
- Regexp.FindStringIndex
- Regexp.FindStringSubmatch
- Regexp.FindSubmatch
- Regexp.FindSubmatchIndex
- Regexp.Longest
- Regexp.Match
- Regexp.MatchString
- Regexp.NumSubexp
- Regexp.ReplaceAll
- Regexp.ReplaceAllLiteralString
- Regexp.ReplaceAllString
- Regexp.ReplaceAllStringFunc
- Regexp.Split
- Regexp.SubexpIndex
- Regexp.SubexpNames
Constants¶
This section is empty.
Variables¶
This section is empty.
Functions¶
funcMatch¶
Match reports whether the byte slice bcontains any match of the regular expression pattern.More complicated queries need to useCompile and the fullRegexp interface.
Example¶
package mainimport ("fmt""regexp")func main() {matched, err := regexp.Match(`foo.*`, []byte(`seafood`))fmt.Println(matched, err)matched, err = regexp.Match(`bar.*`, []byte(`seafood`))fmt.Println(matched, err)matched, err = regexp.Match(`a(b`, []byte(`seafood`))fmt.Println(matched, err)}Output:true <nil>false <nil>false error parsing regexp: missing closing ): `a(b`
funcMatchReader¶
func MatchReader(patternstring, rio.RuneReader) (matchedbool, errerror)
MatchReader reports whether the text returned by theio.RuneReadercontains any match of the regular expression pattern.More complicated queries need to useCompile and the fullRegexp interface.
funcMatchString¶
MatchString reports whether the string scontains any match of the regular expression pattern.More complicated queries need to useCompile and the fullRegexp interface.
Example¶
package mainimport ("fmt""regexp")func main() {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`
funcQuoteMeta¶
QuoteMeta returns a string that escapes all regular expression metacharactersinside the argument text; the returned string is a regular expression matchingthe literal text.
Example¶
package mainimport ("fmt""regexp")func main() {fmt.Println(regexp.QuoteMeta(`Escaping symbols like: .+*?()|[]{}^$`))}Output:Escaping symbols like: \.\+\*\?\(\)\|\[\]\{\}\^\$
Types¶
typeRegexp¶
type Regexp struct {// contains filtered or unexported fields}Regexp is the representation of a compiled regular expression.A Regexp is safe for concurrent use by multiple goroutines,except for configuration methods, such asRegexp.Longest.
funcCompile¶
Compile parses a regular expression and returns, if successful,aRegexp object that can be used to match against text.
When matching against text, the regexp returns a match thatbegins as early as possible in the input (leftmost), and among thoseit chooses the one that a backtracking search would have found first.This so-called leftmost-first matching is the same semanticsthat Perl, Python, and other implementations use, although thispackage implements it without the expense of backtracking.For POSIX leftmost-longest matching, seeCompilePOSIX.
funcCompilePOSIX¶
CompilePOSIX is likeCompile but restricts the regular expressionto POSIX ERE (egrep) syntax and changes the match semantics toleftmost-longest.
That is, when matching against text, the regexp returns a match thatbegins as early as possible in the input (leftmost), and among thoseit chooses a match that is as long as possible.This so-called leftmost-longest matching is the same semanticsthat early regular expression implementations used and that POSIXspecifies.
However, there can be multiple leftmost-longest matches, with differentsubmatch choices, and here this package diverges from POSIX.Among the possible leftmost-longest matches, this package choosesthe one that a backtracking search would have found first, while POSIXspecifies that the match be chosen to maximize the length of the firstsubexpression, then the second, and so on from left to right.The POSIX rule is computationally prohibitive and not even well-defined.Seehttps://swtch.com/~rsc/regexp/regexp2.html#posix for details.
funcMustCompile¶
MustCompile is likeCompile but panics if the expression cannot be parsed.It simplifies safe initialization of global variables holding compiled regularexpressions.
funcMustCompilePOSIX¶
MustCompilePOSIX is likeCompilePOSIX but panics if the expression cannot be parsed.It simplifies safe initialization of global variables holding compiled regularexpressions.
func (*Regexp)AppendText¶added ingo1.24.0
AppendText implementsencoding.TextAppender. The outputmatches that of calling theRegexp.String method.
Note that the output is lossy in some cases: This method does not indicatePOSIX regular expressions (i.e. those compiled by callingCompilePOSIX), orthose for which theRegexp.Longest method has been called.
func (*Regexp)Copydeprecatedadded ingo1.6
Copy returns a newRegexp object copied from re.CallingRegexp.Longest on one copy does not affect another.
Deprecated: In earlier releases, when using aRegexp 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 maketwo copies with differentRegexp.Longest settings.
func (*Regexp)Expand¶
Expand appends template to dst and returns the result; during theappend, Expand replaces variables in the template with correspondingmatches drawn from src. The match slice should have been returned byRegexp.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 tothe submatch with the corresponding index; other names refer tocapturing parentheses named with the (?P<name>...) syntax. Areference to an out of range or unmatched index or a name that is notpresent in the regular expression is replaced with an empty slice.
In the $name form, name is taken to be as long as possible: $1x isequivalent 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.
Example¶
package mainimport ("fmt""regexp")func main() {content := []byte(`# comment lineoption1: value1option2: value2# another comment lineoption3: value3`)// Regex pattern captures "key: value" pair from the content.pattern := regexp.MustCompile(`(?m)(?P<key>\w+):\s+(?P<value>\w+)$`)// Template to convert "key: value" to "key=value" by// referencing the values captured by the regex pattern.template := []byte("$key=$value\n")result := []byte{}// For each match of the regex in the content.for _, submatches := range pattern.FindAllSubmatchIndex(content, -1) {// Apply the captured submatches to the template and append the output// to the result.result = pattern.Expand(result, template, content, submatches)}fmt.Println(string(result))}Output:option1=value1option2=value2option3=value3
func (*Regexp)ExpandString¶
ExpandString is likeRegexp.Expand but the template and source are strings.It appends to and returns a byte slice in order to give the callingcode control over allocation.
Example¶
package mainimport ("fmt""regexp")func main() {content := `# comment lineoption1: value1option2: value2# another comment lineoption3: value3`// Regex pattern captures "key: value" pair from the content.pattern := regexp.MustCompile(`(?m)(?P<key>\w+):\s+(?P<value>\w+)$`)// Template to convert "key: value" to "key=value" by// referencing the values captured by the regex pattern.template := "$key=$value\n"result := []byte{}// For each match of the regex in the content.for _, submatches := range pattern.FindAllStringSubmatchIndex(content, -1) {// Apply the captured submatches to the template and append the output// to the result.result = pattern.ExpandString(result, template, content, submatches)}fmt.Println(string(result))}Output:option1=value1option2=value2option3=value3
func (*Regexp)Find¶
Find returns a slice holding the text of the leftmost match in b of the regular expression.A return value of nil indicates no match.
Example¶
package mainimport ("fmt""regexp")func main() {re := regexp.MustCompile(`foo.?`)fmt.Printf("%q\n", re.Find([]byte(`seafood fool`)))}Output:"food"
func (*Regexp)FindAll¶
FindAll is the 'All' version ofRegexp.Find; it returns a slice of all successivematches of the expression, as defined by the 'All' description in thepackage comment.A return value of nil indicates no match.
Example¶
package mainimport ("fmt""regexp")func main() {re := regexp.MustCompile(`foo.?`)fmt.Printf("%q\n", re.FindAll([]byte(`seafood fool`), -1))}Output:["food" "fool"]
func (*Regexp)FindAllIndex¶
FindAllIndex is the 'All' version ofRegexp.FindIndex; it returns a slice of allsuccessive matches of the expression, as defined by the 'All' descriptionin the package comment.A return value of nil indicates no match.
Example¶
package mainimport ("fmt""regexp")func main() {content := []byte("London")re := regexp.MustCompile(`o.`)fmt.Println(re.FindAllIndex(content, 1))fmt.Println(re.FindAllIndex(content, -1))}Output:[[1 3]][[1 3] [4 6]]
func (*Regexp)FindAllString¶
FindAllString is the 'All' version ofRegexp.FindString; it returns a slice of allsuccessive matches of the expression, as defined by the 'All' descriptionin the package comment.A return value of nil indicates no match.
Example¶
package mainimport ("fmt""regexp")func main() {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][]
func (*Regexp)FindAllStringIndex¶
FindAllStringIndex is the 'All' version ofRegexp.FindStringIndex; it returns aslice 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 (*Regexp)FindAllStringSubmatch¶
FindAllStringSubmatch is the 'All' version ofRegexp.FindStringSubmatch; itreturns a slice of all successive matches of the expression, as defined bythe 'All' description in the package comment.A return value of nil indicates no match.
Example¶
package mainimport ("fmt""regexp")func main() {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" ""]]
func (*Regexp)FindAllStringSubmatchIndex¶
FindAllStringSubmatchIndex is the 'All' version ofRegexp.FindStringSubmatchIndex; it returns a slice of all successive matches ofthe expression, as defined by the 'All' description in the packagecomment.A return value of nil indicates no match.
Example¶
package mainimport ("fmt""regexp")func main() {re := regexp.MustCompile(`a(x*)b`)// Indices:// 01234567 012345678// -ab-axb- -axxb-ab-fmt.Println(re.FindAllStringSubmatchIndex("-ab-", -1))fmt.Println(re.FindAllStringSubmatchIndex("-axxb-", -1))fmt.Println(re.FindAllStringSubmatchIndex("-ab-axb-", -1))fmt.Println(re.FindAllStringSubmatchIndex("-axxb-ab-", -1))fmt.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 (*Regexp)FindAllSubmatch¶
FindAllSubmatch is the 'All' version ofRegexp.FindSubmatch; it returns a sliceof all successive matches of the expression, as defined by the 'All'description in the package comment.A return value of nil indicates no match.
Example¶
package mainimport ("fmt""regexp")func main() {re := regexp.MustCompile(`foo(.?)`)fmt.Printf("%q\n", re.FindAllSubmatch([]byte(`seafood fool`), -1))}Output:[["food" "d"] ["fool" "l"]]
func (*Regexp)FindAllSubmatchIndex¶
FindAllSubmatchIndex is the 'All' version ofRegexp.FindSubmatchIndex; it returnsa 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.
Example¶
package mainimport ("fmt""regexp")func main() {content := []byte(`# comment lineoption1: value1option2: value2`)// Regex pattern captures "key: value" pair from the content.pattern := regexp.MustCompile(`(?m)(?P<key>\w+):\s+(?P<value>\w+)$`)allIndexes := pattern.FindAllSubmatchIndex(content, -1)for _, loc := range allIndexes {fmt.Println(loc)fmt.Println(string(content[loc[0]:loc[1]]))fmt.Println(string(content[loc[2]:loc[3]]))fmt.Println(string(content[loc[4]:loc[5]]))}}Output:[18 33 18 25 27 33]option1: value1option1value1[35 50 35 42 44 50]option2: value2option2value2
func (*Regexp)FindIndex¶
FindIndex returns a two-element slice of integers defining the location ofthe leftmost match in b of the regular expression. The match itself is atb[loc[0]:loc[1]].A return value of nil indicates no match.
Example¶
package mainimport ("fmt""regexp")func main() {content := []byte(`# comment lineoption1: value1option2: value2`)// Regex pattern captures "key: value" pair from the content.pattern := regexp.MustCompile(`(?m)(?P<key>\w+):\s+(?P<value>\w+)$`)loc := pattern.FindIndex(content)fmt.Println(loc)fmt.Println(string(content[loc[0]:loc[1]]))}Output:[18 33]option1: value1
func (*Regexp)FindReaderIndex¶
func (re *Regexp) FindReaderIndex(rio.RuneReader) (loc []int)
FindReaderIndex returns a two-element slice of integers defining thelocation of the leftmost match of the regular expression in text read fromtheio.RuneReader. The match text was found in the input stream atbyte offset loc[0] through loc[1]-1.A return value of nil indicates no match.
func (*Regexp)FindReaderSubmatchIndex¶
func (re *Regexp) FindReaderSubmatchIndex(rio.RuneReader) []int
FindReaderSubmatchIndex returns a slice holding the index pairsidentifying the leftmost match of the regular expression of text read bytheio.RuneReader, and the matches, if any, of its subexpressions, as definedby the 'Submatch' and 'Index' descriptions in the package comment. Areturn value of nil indicates no match.
func (*Regexp)FindString¶
FindString returns a string holding the text of the leftmost match in s of the regularexpression. If there is no match, the return value is an empty string,but it will also be empty if the regular expression successfully matchesan empty string. UseRegexp.FindStringIndex orRegexp.FindStringSubmatch if it isnecessary to distinguish these cases.
Example¶
package mainimport ("fmt""regexp")func main() {re := regexp.MustCompile(`foo.?`)fmt.Printf("%q\n", re.FindString("seafood fool"))fmt.Printf("%q\n", re.FindString("meat"))}Output:"food"""
func (*Regexp)FindStringIndex¶
FindStringIndex returns a two-element slice of integers defining thelocation of the leftmost match in s of the regular expression. The matchitself is at s[loc[0]:loc[1]].A return value of nil indicates no match.
Example¶
package mainimport ("fmt""regexp")func main() {re := regexp.MustCompile(`ab?`)fmt.Println(re.FindStringIndex("tablett"))fmt.Println(re.FindStringIndex("foo") == nil)}Output:[1 3]true
func (*Regexp)FindStringSubmatch¶
FindStringSubmatch returns a slice of strings holding the text of theleftmost match of the regular expression in s and the matches, if any, ofits subexpressions, as defined by the 'Submatch' description in thepackage comment.A return value of nil indicates no match.
Example¶
package mainimport ("fmt""regexp")func main() {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"]
func (*Regexp)FindStringSubmatchIndex¶
FindStringSubmatchIndex returns a slice holding the index pairsidentifying the leftmost match of the regular expression in s and thematches, 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 (*Regexp)FindSubmatch¶
FindSubmatch returns a slice of slices holding the text of the leftmostmatch of the regular expression in b and the matches, if any, of itssubexpressions, as defined by the 'Submatch' descriptions in the packagecomment.A return value of nil indicates no match.
Example¶
package mainimport ("fmt""regexp")func main() {re := regexp.MustCompile(`foo(.?)`)fmt.Printf("%q\n", re.FindSubmatch([]byte(`seafood fool`)))}Output:["food" "d"]
func (*Regexp)FindSubmatchIndex¶
FindSubmatchIndex returns a slice holding the index pairs identifying theleftmost match of the regular expression in b and the matches, if any, ofits subexpressions, as defined by the 'Submatch' and 'Index' descriptionsin the package comment.A return value of nil indicates no match.
Example¶
package mainimport ("fmt""regexp")func main() {re := regexp.MustCompile(`a(x*)b`)// Indices:// 01234567 012345678// -ab-axb- -axxb-ab-fmt.Println(re.FindSubmatchIndex([]byte("-ab-")))fmt.Println(re.FindSubmatchIndex([]byte("-axxb-")))fmt.Println(re.FindSubmatchIndex([]byte("-ab-axb-")))fmt.Println(re.FindSubmatchIndex([]byte("-axxb-ab-")))fmt.Println(re.FindSubmatchIndex([]byte("-foo-")))}Output:[1 3 2 2][1 5 2 4][1 3 2 2][1 5 2 4][]
func (*Regexp)LiteralPrefix¶
LiteralPrefix returns a literal string that must begin any matchof the regular expression re. It returns the boolean true if theliteral string comprises the entire regular expression.
func (*Regexp)Longest¶added ingo1.1
func (re *Regexp) Longest()
Longest makes future searches prefer the leftmost-longest match.That is, when matching against text, the regexp returns a match thatbegins as early as possible in the input (leftmost), and among thoseit chooses a match that is as long as possible.This method modifies theRegexp and may not be called concurrentlywith any other methods.
Example¶
package mainimport ("fmt""regexp")func main() {re := regexp.MustCompile(`a(|b)`)fmt.Println(re.FindString("ab"))re.Longest()fmt.Println(re.FindString("ab"))}Output:aab
func (*Regexp)MarshalText¶added ingo1.21.0
MarshalText implementsencoding.TextMarshaler. The outputmatches that of calling theRegexp.AppendText method.
SeeRegexp.AppendText for more information.
func (*Regexp)Match¶
Match reports whether the byte slice bcontains any match of the regular expression re.
Example¶
package mainimport ("fmt""regexp")func main() {re := regexp.MustCompile(`foo.?`)fmt.Println(re.Match([]byte(`seafood fool`)))fmt.Println(re.Match([]byte(`something else`)))}Output:truefalse
func (*Regexp)MatchReader¶
func (re *Regexp) MatchReader(rio.RuneReader)bool
MatchReader reports whether the text returned by theio.RuneReadercontains any match of the regular expression re.
func (*Regexp)MatchString¶
MatchString reports whether the string scontains any match of the regular expression re.
Example¶
package mainimport ("fmt""regexp")func main() {re := regexp.MustCompile(`(gopher){2}`)fmt.Println(re.MatchString("gopher"))fmt.Println(re.MatchString("gophergopher"))fmt.Println(re.MatchString("gophergophergopher"))}Output:falsetruetrue
func (*Regexp)NumSubexp¶
NumSubexp returns the number of parenthesized subexpressions in thisRegexp.
Example¶
package mainimport ("fmt""regexp")func main() {re0 := regexp.MustCompile(`a.`)fmt.Printf("%d\n", re0.NumSubexp())re := regexp.MustCompile(`(.*)((a)b)(.*)a`)fmt.Println(re.NumSubexp())}Output:04
func (*Regexp)ReplaceAll¶
ReplaceAll returns a copy of src, replacing matches of theRegexpwith the replacement text repl.Inside repl, $ signs are interpreted as inRegexp.Expand.
Example¶
package mainimport ("fmt""regexp")func main() {re := regexp.MustCompile(`a(x*)b`)fmt.Printf("%s\n", re.ReplaceAll([]byte("-ab-axxb-"), []byte("T")))fmt.Printf("%s\n", re.ReplaceAll([]byte("-ab-axxb-"), []byte("$1")))fmt.Printf("%s\n", re.ReplaceAll([]byte("-ab-axxb-"), []byte("$1W")))fmt.Printf("%s\n", re.ReplaceAll([]byte("-ab-axxb-"), []byte("${1}W")))re2 := regexp.MustCompile(`a(?P<1W>x*)b`)fmt.Printf("%s\n", re2.ReplaceAll([]byte("-ab-axxb-"), []byte("$1W")))fmt.Printf("%s\n", re2.ReplaceAll([]byte("-ab-axxb-"), []byte("${1}W")))}Output:-T-T---xx-----W-xxW---xx--W-xxW-
func (*Regexp)ReplaceAllFunc¶
ReplaceAllFunc returns a copy of src in which all matches of theRegexp have been replaced by the return value of function repl appliedto the matched byte slice. The replacement returned by repl is substituteddirectly, without usingRegexp.Expand.
func (*Regexp)ReplaceAllLiteral¶
ReplaceAllLiteral returns a copy of src, replacing matches of theRegexpwith the replacement bytes repl. The replacement repl is substituted directly,without usingRegexp.Expand.
func (*Regexp)ReplaceAllLiteralString¶
ReplaceAllLiteralString returns a copy of src, replacing matches of theRegexpwith the replacement string repl. The replacement repl is substituted directly,without usingRegexp.Expand.
Example¶
package mainimport ("fmt""regexp")func main() {re := regexp.MustCompile(`a(x*)b`)fmt.Println(re.ReplaceAllLiteralString("-ab-axxb-", "T"))fmt.Println(re.ReplaceAllLiteralString("-ab-axxb-", "$1"))fmt.Println(re.ReplaceAllLiteralString("-ab-axxb-", "${1}"))}Output:-T-T--$1-$1--${1}-${1}-
func (*Regexp)ReplaceAllString¶
ReplaceAllString returns a copy of src, replacing matches of theRegexpwith the replacement string repl.Inside repl, $ signs are interpreted as inRegexp.Expand.
Example¶
package mainimport ("fmt""regexp")func main() {re := regexp.MustCompile(`a(x*)b`)fmt.Println(re.ReplaceAllString("-ab-axxb-", "T"))fmt.Println(re.ReplaceAllString("-ab-axxb-", "$1"))fmt.Println(re.ReplaceAllString("-ab-axxb-", "$1W"))fmt.Println(re.ReplaceAllString("-ab-axxb-", "${1}W"))re2 := regexp.MustCompile(`a(?P<1W>x*)b`)fmt.Printf("%s\n", re2.ReplaceAllString("-ab-axxb-", "$1W"))fmt.Println(re.ReplaceAllString("-ab-axxb-", "${1}W"))}Output:-T-T---xx-----W-xxW---xx--W-xxW-
func (*Regexp)ReplaceAllStringFunc¶
ReplaceAllStringFunc returns a copy of src in which all matches of theRegexp have been replaced by the return value of function repl appliedto the matched substring. The replacement returned by repl is substituteddirectly, without usingRegexp.Expand.
Example¶
package mainimport ("fmt""regexp""strings")func main() {re := regexp.MustCompile(`[^aeiou]`)fmt.Println(re.ReplaceAllStringFunc("seafood fool", strings.ToUpper))}Output:SeaFooD FooL
func (*Regexp)Split¶added ingo1.1
Split slices s into substrings separated by the expression and returns a slice ofthe substrings between those expression matches.
The slice returned by this method consists of all the substrings of snot contained in the slice returned byRegexp.FindAllString. When called on an expressionthat contains no metacharacters, it is equivalent tostrings.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.
Example¶
package mainimport ("fmt""regexp")func main() {a := regexp.MustCompile(`a`)fmt.Println(a.Split("banana", -1))fmt.Println(a.Split("banana", 0))fmt.Println(a.Split("banana", 1))fmt.Println(a.Split("banana", 2))zp := regexp.MustCompile(`z+`)fmt.Println(zp.Split("pizza", -1))fmt.Println(zp.Split("pizza", 0))fmt.Println(zp.Split("pizza", 1))fmt.Println(zp.Split("pizza", 2))}Output:[b n n ][][banana][b nana][pi a][][pizza][pi a]
func (*Regexp)SubexpIndex¶added ingo1.15
SubexpIndex 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<bob>a+)(?P<bob>b+), which declares two subexpressions named "bob".In this case, SubexpIndex returns the index of the leftmost such subexpressionin the regular expression.
Example¶
package mainimport ("fmt""regexp")func main() {re := regexp.MustCompile(`(?P<first>[a-zA-Z]+) (?P<last>[a-zA-Z]+)`)fmt.Println(re.MatchString("Alan Turing"))matches := re.FindStringSubmatch("Alan Turing")lastIndex := re.SubexpIndex("last")fmt.Printf("last => %d\n", lastIndex)fmt.Println(matches[lastIndex])}Output:truelast => 2Turing
func (*Regexp)SubexpNames¶
SubexpNames returns the names of the parenthesized subexpressionsin thisRegexp. 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 alwaysthe empty string. The slice should not be modified.
Example¶
package mainimport ("fmt""regexp")func main() {re := regexp.MustCompile(`(?P<first>[a-zA-Z]+) (?P<last>[a-zA-Z]+)`)fmt.Println(re.MatchString("Alan Turing"))fmt.Printf("%q\n", re.SubexpNames())reversed := fmt.Sprintf("${%s} ${%s}", re.SubexpNames()[2], re.SubexpNames()[1])fmt.Println(reversed)fmt.Println(re.ReplaceAllString("Alan Turing", reversed))}Output:true["" "first" "last"]${last} ${first}Turing Alan
func (*Regexp)UnmarshalText¶added ingo1.21.0
UnmarshalText implementsencoding.TextUnmarshaler by callingCompile on the encoded value.