github.com/tidwall/go@v0.0.0-20170415222209-6694a6888b7d/src/regexp/regexp.go (about)

     1  // Copyright 2009 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // Package regexp implements regular expression search.
     6  //
     7  // The syntax of the regular expressions accepted is the same
     8  // general syntax used by Perl, Python, and other languages.
     9  // More precisely, it is the syntax accepted by RE2 and described at
    10  // https://golang.org/s/re2syntax, except for \C.
    11  // For an overview of the syntax, run
    12  //   go doc regexp/syntax
    13  //
    14  // The regexp implementation provided by this package is
    15  // guaranteed to run in time linear in the size of the input.
    16  // (This is a property not guaranteed by most open source
    17  // implementations of regular expressions.) For more information
    18  // about this property, see
    19  //	http://swtch.com/~rsc/regexp/regexp1.html
    20  // or any book about automata theory.
    21  //
    22  // All characters are UTF-8-encoded code points.
    23  //
    24  // There are 16 methods of Regexp that match a regular expression and identify
    25  // the matched text. Their names are matched by this regular expression:
    26  //
    27  //	Find(All)?(String)?(Submatch)?(Index)?
    28  //
    29  // If 'All' is present, the routine matches successive non-overlapping
    30  // matches of the entire expression. Empty matches abutting a preceding
    31  // match are ignored. The return value is a slice containing the successive
    32  // return values of the corresponding non-'All' routine. These routines take
    33  // an extra integer argument, n; if n >= 0, the function returns at most n
    34  // matches/submatches.
    35  //
    36  // If 'String' is present, the argument is a string; otherwise it is a slice
    37  // of bytes; return values are adjusted as appropriate.
    38  //
    39  // If 'Submatch' is present, the return value is a slice identifying the
    40  // successive submatches of the expression. Submatches are matches of
    41  // parenthesized subexpressions (also known as capturing groups) within the
    42  // regular expression, numbered from left to right in order of opening
    43  // parenthesis. Submatch 0 is the match of the entire expression, submatch 1
    44  // the match of the first parenthesized subexpression, and so on.
    45  //
    46  // If 'Index' is present, matches and submatches are identified by byte index
    47  // pairs within the input string: result[2*n:2*n+1] identifies the indexes of
    48  // the nth submatch. The pair for n==0 identifies the match of the entire
    49  // expression. If 'Index' is not present, the match is identified by the
    50  // text of the match/submatch. If an index is negative, it means that
    51  // subexpression did not match any string in the input.
    52  //
    53  // There is also a subset of the methods that can be applied to text read
    54  // from a RuneReader:
    55  //
    56  //	MatchReader, FindReaderIndex, FindReaderSubmatchIndex
    57  //
    58  // This set may grow. Note that regular expression matches may need to
    59  // examine text beyond the text returned by a match, so the methods that
    60  // match text from a RuneReader may read arbitrarily far into the input
    61  // before returning.
    62  //
    63  // (There are a few other methods that do not match this pattern.)
    64  //
    65  package regexp
    66  
    67  import (
    68  	"bytes"
    69  	"io"
    70  	"regexp/syntax"
    71  	"strconv"
    72  	"strings"
    73  	"sync"
    74  	"unicode"
    75  	"unicode/utf8"
    76  )
    77  
    78  // Regexp is the representation of a compiled regular expression.
    79  // A Regexp is safe for concurrent use by multiple goroutines,
    80  // except for configuration methods, such as Longest.
    81  type Regexp struct {
    82  	// read-only after Compile
    83  	regexpRO
    84  
    85  	// cache of machines for running regexp
    86  	mu      sync.Mutex
    87  	machine []*machine
    88  }
    89  
    90  type regexpRO struct {
    91  	expr           string         // as passed to Compile
    92  	prog           *syntax.Prog   // compiled program
    93  	onepass        *onePassProg   // onepass program or nil
    94  	prefix         string         // required prefix in unanchored matches
    95  	prefixBytes    []byte         // prefix, as a []byte
    96  	prefixComplete bool           // prefix is the entire regexp
    97  	prefixRune     rune           // first rune in prefix
    98  	prefixEnd      uint32         // pc for last rune in prefix
    99  	cond           syntax.EmptyOp // empty-width conditions required at start of match
   100  	numSubexp      int
   101  	subexpNames    []string
   102  	longest        bool
   103  }
   104  
   105  // String returns the source text used to compile the regular expression.
   106  func (re *Regexp) String() string {
   107  	return re.expr
   108  }
   109  
   110  // Copy returns a new Regexp object copied from re.
   111  //
   112  // When using a Regexp in multiple goroutines, giving each goroutine
   113  // its own copy helps to avoid lock contention.
   114  func (re *Regexp) Copy() *Regexp {
   115  	// It is not safe to copy Regexp by value
   116  	// since it contains a sync.Mutex.
   117  	return &Regexp{
   118  		regexpRO: re.regexpRO,
   119  	}
   120  }
   121  
   122  // Compile parses a regular expression and returns, if successful,
   123  // a Regexp object that can be used to match against text.
   124  //
   125  // When matching against text, the regexp returns a match that
   126  // begins as early as possible in the input (leftmost), and among those
   127  // it chooses the one that a backtracking search would have found first.
   128  // This so-called leftmost-first matching is the same semantics
   129  // that Perl, Python, and other implementations use, although this
   130  // package implements it without the expense of backtracking.
   131  // For POSIX leftmost-longest matching, see CompilePOSIX.
   132  func Compile(expr string) (*Regexp, error) {
   133  	return compile(expr, syntax.Perl, false)
   134  }
   135  
   136  // CompilePOSIX is like Compile but restricts the regular expression
   137  // to POSIX ERE (egrep) syntax and changes the match semantics to
   138  // leftmost-longest.
   139  //
   140  // That is, when matching against text, the regexp returns a match that
   141  // begins as early as possible in the input (leftmost), and among those
   142  // it chooses a match that is as long as possible.
   143  // This so-called leftmost-longest matching is the same semantics
   144  // that early regular expression implementations used and that POSIX
   145  // specifies.
   146  //
   147  // However, there can be multiple leftmost-longest matches, with different
   148  // submatch choices, and here this package diverges from POSIX.
   149  // Among the possible leftmost-longest matches, this package chooses
   150  // the one that a backtracking search would have found first, while POSIX
   151  // specifies that the match be chosen to maximize the length of the first
   152  // subexpression, then the second, and so on from left to right.
   153  // The POSIX rule is computationally prohibitive and not even well-defined.
   154  // See http://swtch.com/~rsc/regexp/regexp2.html#posix for details.
   155  func CompilePOSIX(expr string) (*Regexp, error) {
   156  	return compile(expr, syntax.POSIX, true)
   157  }
   158  
   159  // Longest makes future searches prefer the leftmost-longest match.
   160  // That is, when matching against text, the regexp returns a match that
   161  // begins as early as possible in the input (leftmost), and among those
   162  // it chooses a match that is as long as possible.
   163  // This method modifies the Regexp and may not be called concurrently
   164  // with any other methods.
   165  func (re *Regexp) Longest() {
   166  	re.longest = true
   167  }
   168  
   169  func compile(expr string, mode syntax.Flags, longest bool) (*Regexp, error) {
   170  	re, err := syntax.Parse(expr, mode)
   171  	if err != nil {
   172  		return nil, err
   173  	}
   174  	maxCap := re.MaxCap()
   175  	capNames := re.CapNames()
   176  
   177  	re = re.Simplify()
   178  	prog, err := syntax.Compile(re)
   179  	if err != nil {
   180  		return nil, err
   181  	}
   182  	regexp := &Regexp{
   183  		regexpRO: regexpRO{
   184  			expr:        expr,
   185  			prog:        prog,
   186  			onepass:     compileOnePass(prog),
   187  			numSubexp:   maxCap,
   188  			subexpNames: capNames,
   189  			cond:        prog.StartCond(),
   190  			longest:     longest,
   191  		},
   192  	}
   193  	if regexp.onepass == notOnePass {
   194  		regexp.prefix, regexp.prefixComplete = prog.Prefix()
   195  	} else {
   196  		regexp.prefix, regexp.prefixComplete, regexp.prefixEnd = onePassPrefix(prog)
   197  	}
   198  	if regexp.prefix != "" {
   199  		// TODO(rsc): Remove this allocation by adding
   200  		// IndexString to package bytes.
   201  		regexp.prefixBytes = []byte(regexp.prefix)
   202  		regexp.prefixRune, _ = utf8.DecodeRuneInString(regexp.prefix)
   203  	}
   204  	return regexp, nil
   205  }
   206  
   207  // get returns a machine to use for matching re.
   208  // It uses the re's machine cache if possible, to avoid
   209  // unnecessary allocation.
   210  func (re *Regexp) get() *machine {
   211  	re.mu.Lock()
   212  	if n := len(re.machine); n > 0 {
   213  		z := re.machine[n-1]
   214  		re.machine = re.machine[:n-1]
   215  		re.mu.Unlock()
   216  		return z
   217  	}
   218  	re.mu.Unlock()
   219  	z := progMachine(re.prog, re.onepass)
   220  	z.re = re
   221  	return z
   222  }
   223  
   224  // put returns a machine to the re's machine cache.
   225  // There is no attempt to limit the size of the cache, so it will
   226  // grow to the maximum number of simultaneous matches
   227  // run using re.  (The cache empties when re gets garbage collected.)
   228  func (re *Regexp) put(z *machine) {
   229  	re.mu.Lock()
   230  	re.machine = append(re.machine, z)
   231  	re.mu.Unlock()
   232  }
   233  
   234  // MustCompile is like Compile but panics if the expression cannot be parsed.
   235  // It simplifies safe initialization of global variables holding compiled regular
   236  // expressions.
   237  func MustCompile(str string) *Regexp {
   238  	regexp, error := Compile(str)
   239  	if error != nil {
   240  		panic(`regexp: Compile(` + quote(str) + `): ` + error.Error())
   241  	}
   242  	return regexp
   243  }
   244  
   245  // MustCompilePOSIX is like CompilePOSIX but panics if the expression cannot be parsed.
   246  // It simplifies safe initialization of global variables holding compiled regular
   247  // expressions.
   248  func MustCompilePOSIX(str string) *Regexp {
   249  	regexp, error := CompilePOSIX(str)
   250  	if error != nil {
   251  		panic(`regexp: CompilePOSIX(` + quote(str) + `): ` + error.Error())
   252  	}
   253  	return regexp
   254  }
   255  
   256  func quote(s string) string {
   257  	if strconv.CanBackquote(s) {
   258  		return "`" + s + "`"
   259  	}
   260  	return strconv.Quote(s)
   261  }
   262  
   263  // NumSubexp returns the number of parenthesized subexpressions in this Regexp.
   264  func (re *Regexp) NumSubexp() int {
   265  	return re.numSubexp
   266  }
   267  
   268  // SubexpNames returns the names of the parenthesized subexpressions
   269  // in this Regexp. The name for the first sub-expression is names[1],
   270  // so that if m is a match slice, the name for m[i] is SubexpNames()[i].
   271  // Since the Regexp as a whole cannot be named, names[0] is always
   272  // the empty string. The slice should not be modified.
   273  func (re *Regexp) SubexpNames() []string {
   274  	return re.subexpNames
   275  }
   276  
   277  const endOfText rune = -1
   278  
   279  // input abstracts different representations of the input text. It provides
   280  // one-character lookahead.
   281  type input interface {
   282  	step(pos int) (r rune, width int) // advance one rune
   283  	canCheckPrefix() bool             // can we look ahead without losing info?
   284  	hasPrefix(re *Regexp) bool
   285  	index(re *Regexp, pos int) int
   286  	context(pos int) syntax.EmptyOp
   287  }
   288  
   289  // inputString scans a string.
   290  type inputString struct {
   291  	str string
   292  }
   293  
   294  func (i *inputString) step(pos int) (rune, int) {
   295  	if pos < len(i.str) {
   296  		c := i.str[pos]
   297  		if c < utf8.RuneSelf {
   298  			return rune(c), 1
   299  		}
   300  		return utf8.DecodeRuneInString(i.str[pos:])
   301  	}
   302  	return endOfText, 0
   303  }
   304  
   305  func (i *inputString) canCheckPrefix() bool {
   306  	return true
   307  }
   308  
   309  func (i *inputString) hasPrefix(re *Regexp) bool {
   310  	return strings.HasPrefix(i.str, re.prefix)
   311  }
   312  
   313  func (i *inputString) index(re *Regexp, pos int) int {
   314  	return strings.Index(i.str[pos:], re.prefix)
   315  }
   316  
   317  func (i *inputString) context(pos int) syntax.EmptyOp {
   318  	r1, r2 := endOfText, endOfText
   319  	// 0 < pos && pos <= len(i.str)
   320  	if uint(pos-1) < uint(len(i.str)) {
   321  		r1 = rune(i.str[pos-1])
   322  		if r1 >= utf8.RuneSelf {
   323  			r1, _ = utf8.DecodeLastRuneInString(i.str[:pos])
   324  		}
   325  	}
   326  	// 0 <= pos && pos < len(i.str)
   327  	if uint(pos) < uint(len(i.str)) {
   328  		r2 = rune(i.str[pos])
   329  		if r2 >= utf8.RuneSelf {
   330  			r2, _ = utf8.DecodeRuneInString(i.str[pos:])
   331  		}
   332  	}
   333  	return syntax.EmptyOpContext(r1, r2)
   334  }
   335  
   336  // inputBytes scans a byte slice.
   337  type inputBytes struct {
   338  	str []byte
   339  }
   340  
   341  func (i *inputBytes) step(pos int) (rune, int) {
   342  	if pos < len(i.str) {
   343  		c := i.str[pos]
   344  		if c < utf8.RuneSelf {
   345  			return rune(c), 1
   346  		}
   347  		return utf8.DecodeRune(i.str[pos:])
   348  	}
   349  	return endOfText, 0
   350  }
   351  
   352  func (i *inputBytes) canCheckPrefix() bool {
   353  	return true
   354  }
   355  
   356  func (i *inputBytes) hasPrefix(re *Regexp) bool {
   357  	return bytes.HasPrefix(i.str, re.prefixBytes)
   358  }
   359  
   360  func (i *inputBytes) index(re *Regexp, pos int) int {
   361  	return bytes.Index(i.str[pos:], re.prefixBytes)
   362  }
   363  
   364  func (i *inputBytes) context(pos int) syntax.EmptyOp {
   365  	r1, r2 := endOfText, endOfText
   366  	// 0 < pos && pos <= len(i.str)
   367  	if uint(pos-1) < uint(len(i.str)) {
   368  		r1 = rune(i.str[pos-1])
   369  		if r1 >= utf8.RuneSelf {
   370  			r1, _ = utf8.DecodeLastRune(i.str[:pos])
   371  		}
   372  	}
   373  	// 0 <= pos && pos < len(i.str)
   374  	if uint(pos) < uint(len(i.str)) {
   375  		r2 = rune(i.str[pos])
   376  		if r2 >= utf8.RuneSelf {
   377  			r2, _ = utf8.DecodeRune(i.str[pos:])
   378  		}
   379  	}
   380  	return syntax.EmptyOpContext(r1, r2)
   381  }
   382  
   383  // inputReader scans a RuneReader.
   384  type inputReader struct {
   385  	r     io.RuneReader
   386  	atEOT bool
   387  	pos   int
   388  }
   389  
   390  func (i *inputReader) step(pos int) (rune, int) {
   391  	if !i.atEOT && pos != i.pos {
   392  		return endOfText, 0
   393  
   394  	}
   395  	r, w, err := i.r.ReadRune()
   396  	if err != nil {
   397  		i.atEOT = true
   398  		return endOfText, 0
   399  	}
   400  	i.pos += w
   401  	return r, w
   402  }
   403  
   404  func (i *inputReader) canCheckPrefix() bool {
   405  	return false
   406  }
   407  
   408  func (i *inputReader) hasPrefix(re *Regexp) bool {
   409  	return false
   410  }
   411  
   412  func (i *inputReader) index(re *Regexp, pos int) int {
   413  	return -1
   414  }
   415  
   416  func (i *inputReader) context(pos int) syntax.EmptyOp {
   417  	return 0
   418  }
   419  
   420  // LiteralPrefix returns a literal string that must begin any match
   421  // of the regular expression re. It returns the boolean true if the
   422  // literal string comprises the entire regular expression.
   423  func (re *Regexp) LiteralPrefix() (prefix string, complete bool) {
   424  	return re.prefix, re.prefixComplete
   425  }
   426  
   427  // MatchReader reports whether the Regexp matches the text read by the
   428  // RuneReader.
   429  func (re *Regexp) MatchReader(r io.RuneReader) bool {
   430  	return re.doMatch(r, nil, "")
   431  }
   432  
   433  // MatchString reports whether the Regexp matches the string s.
   434  func (re *Regexp) MatchString(s string) bool {
   435  	return re.doMatch(nil, nil, s)
   436  }
   437  
   438  // Match reports whether the Regexp matches the byte slice b.
   439  func (re *Regexp) Match(b []byte) bool {
   440  	return re.doMatch(nil, b, "")
   441  }
   442  
   443  // MatchReader checks whether a textual regular expression matches the text
   444  // read by the RuneReader. More complicated queries need to use Compile and
   445  // the full Regexp interface.
   446  func MatchReader(pattern string, r io.RuneReader) (matched bool, err error) {
   447  	re, err := Compile(pattern)
   448  	if err != nil {
   449  		return false, err
   450  	}
   451  	return re.MatchReader(r), nil
   452  }
   453  
   454  // MatchString checks whether a textual regular expression
   455  // matches a string. More complicated queries need
   456  // to use Compile and the full Regexp interface.
   457  func MatchString(pattern string, s string) (matched bool, err error) {
   458  	re, err := Compile(pattern)
   459  	if err != nil {
   460  		return false, err
   461  	}
   462  	return re.MatchString(s), nil
   463  }
   464  
   465  // Match checks whether a textual regular expression
   466  // matches a byte slice. More complicated queries need
   467  // to use Compile and the full Regexp interface.
   468  func Match(pattern string, b []byte) (matched bool, err error) {
   469  	re, err := Compile(pattern)
   470  	if err != nil {
   471  		return false, err
   472  	}
   473  	return re.Match(b), nil
   474  }
   475  
   476  // ReplaceAllString returns a copy of src, replacing matches of the Regexp
   477  // with the replacement string repl. Inside repl, $ signs are interpreted as
   478  // in Expand, so for instance $1 represents the text of the first submatch.
   479  func (re *Regexp) ReplaceAllString(src, repl string) string {
   480  	n := 2
   481  	if strings.Contains(repl, "$") {
   482  		n = 2 * (re.numSubexp + 1)
   483  	}
   484  	b := re.replaceAll(nil, src, n, func(dst []byte, match []int) []byte {
   485  		return re.expand(dst, repl, nil, src, match)
   486  	})
   487  	return string(b)
   488  }
   489  
   490  // ReplaceAllLiteralString returns a copy of src, replacing matches of the Regexp
   491  // with the replacement string repl. The replacement repl is substituted directly,
   492  // without using Expand.
   493  func (re *Regexp) ReplaceAllLiteralString(src, repl string) string {
   494  	return string(re.replaceAll(nil, src, 2, func(dst []byte, match []int) []byte {
   495  		return append(dst, repl...)
   496  	}))
   497  }
   498  
   499  // ReplaceAllStringFunc returns a copy of src in which all matches of the
   500  // Regexp have been replaced by the return value of function repl applied
   501  // to the matched substring. The replacement returned by repl is substituted
   502  // directly, without using Expand.
   503  func (re *Regexp) ReplaceAllStringFunc(src string, repl func(string) string) string {
   504  	b := re.replaceAll(nil, src, 2, func(dst []byte, match []int) []byte {
   505  		return append(dst, repl(src[match[0]:match[1]])...)
   506  	})
   507  	return string(b)
   508  }
   509  
   510  func (re *Regexp) replaceAll(bsrc []byte, src string, nmatch int, repl func(dst []byte, m []int) []byte) []byte {
   511  	lastMatchEnd := 0 // end position of the most recent match
   512  	searchPos := 0    // position where we next look for a match
   513  	var buf []byte
   514  	var endPos int
   515  	if bsrc != nil {
   516  		endPos = len(bsrc)
   517  	} else {
   518  		endPos = len(src)
   519  	}
   520  	if nmatch > re.prog.NumCap {
   521  		nmatch = re.prog.NumCap
   522  	}
   523  
   524  	var dstCap [2]int
   525  	for searchPos <= endPos {
   526  		a := re.doExecute(nil, bsrc, src, searchPos, nmatch, dstCap[:0])
   527  		if len(a) == 0 {
   528  			break // no more matches
   529  		}
   530  
   531  		// Copy the unmatched characters before this match.
   532  		if bsrc != nil {
   533  			buf = append(buf, bsrc[lastMatchEnd:a[0]]...)
   534  		} else {
   535  			buf = append(buf, src[lastMatchEnd:a[0]]...)
   536  		}
   537  
   538  		// Now insert a copy of the replacement string, but not for a
   539  		// match of the empty string immediately after another match.
   540  		// (Otherwise, we get double replacement for patterns that
   541  		// match both empty and nonempty strings.)
   542  		if a[1] > lastMatchEnd || a[0] == 0 {
   543  			buf = repl(buf, a)
   544  		}
   545  		lastMatchEnd = a[1]
   546  
   547  		// Advance past this match; always advance at least one character.
   548  		var width int
   549  		if bsrc != nil {
   550  			_, width = utf8.DecodeRune(bsrc[searchPos:])
   551  		} else {
   552  			_, width = utf8.DecodeRuneInString(src[searchPos:])
   553  		}
   554  		if searchPos+width > a[1] {
   555  			searchPos += width
   556  		} else if searchPos+1 > a[1] {
   557  			// This clause is only needed at the end of the input
   558  			// string. In that case, DecodeRuneInString returns width=0.
   559  			searchPos++
   560  		} else {
   561  			searchPos = a[1]
   562  		}
   563  	}
   564  
   565  	// Copy the unmatched characters after the last match.
   566  	if bsrc != nil {
   567  		buf = append(buf, bsrc[lastMatchEnd:]...)
   568  	} else {
   569  		buf = append(buf, src[lastMatchEnd:]...)
   570  	}
   571  
   572  	return buf
   573  }
   574  
   575  // ReplaceAll returns a copy of src, replacing matches of the Regexp
   576  // with the replacement text repl. Inside repl, $ signs are interpreted as
   577  // in Expand, so for instance $1 represents the text of the first submatch.
   578  func (re *Regexp) ReplaceAll(src, repl []byte) []byte {
   579  	n := 2
   580  	if bytes.IndexByte(repl, '$') >= 0 {
   581  		n = 2 * (re.numSubexp + 1)
   582  	}
   583  	srepl := ""
   584  	b := re.replaceAll(src, "", n, func(dst []byte, match []int) []byte {
   585  		if len(srepl) != len(repl) {
   586  			srepl = string(repl)
   587  		}
   588  		return re.expand(dst, srepl, src, "", match)
   589  	})
   590  	return b
   591  }
   592  
   593  // ReplaceAllLiteral returns a copy of src, replacing matches of the Regexp
   594  // with the replacement bytes repl. The replacement repl is substituted directly,
   595  // without using Expand.
   596  func (re *Regexp) ReplaceAllLiteral(src, repl []byte) []byte {
   597  	return re.replaceAll(src, "", 2, func(dst []byte, match []int) []byte {
   598  		return append(dst, repl...)
   599  	})
   600  }
   601  
   602  // ReplaceAllFunc returns a copy of src in which all matches of the
   603  // Regexp have been replaced by the return value of function repl applied
   604  // to the matched byte slice. The replacement returned by repl is substituted
   605  // directly, without using Expand.
   606  func (re *Regexp) ReplaceAllFunc(src []byte, repl func([]byte) []byte) []byte {
   607  	return re.replaceAll(src, "", 2, func(dst []byte, match []int) []byte {
   608  		return append(dst, repl(src[match[0]:match[1]])...)
   609  	})
   610  }
   611  
   612  var specialBytes = []byte(`\.+*?()|[]{}^$`)
   613  
   614  func special(b byte) bool {
   615  	return bytes.IndexByte(specialBytes, b) >= 0
   616  }
   617  
   618  // QuoteMeta returns a string that quotes all regular expression metacharacters
   619  // inside the argument text; the returned string is a regular expression matching
   620  // the literal text. For example, QuoteMeta(`[foo]`) returns `\[foo\]`.
   621  func QuoteMeta(s string) string {
   622  	// A byte loop is correct because all metacharacters are ASCII.
   623  	var i int
   624  	for i = 0; i < len(s); i++ {
   625  		if special(s[i]) {
   626  			break
   627  		}
   628  	}
   629  	// No meta characters found, so return original string.
   630  	if i >= len(s) {
   631  		return s
   632  	}
   633  
   634  	b := make([]byte, 2*len(s)-i)
   635  	copy(b, s[:i])
   636  	j := i
   637  	for ; i < len(s); i++ {
   638  		if special(s[i]) {
   639  			b[j] = '\\'
   640  			j++
   641  		}
   642  		b[j] = s[i]
   643  		j++
   644  	}
   645  	return string(b[:j])
   646  }
   647  
   648  // The number of capture values in the program may correspond
   649  // to fewer capturing expressions than are in the regexp.
   650  // For example, "(a){0}" turns into an empty program, so the
   651  // maximum capture in the program is 0 but we need to return
   652  // an expression for \1.  Pad appends -1s to the slice a as needed.
   653  func (re *Regexp) pad(a []int) []int {
   654  	if a == nil {
   655  		// No match.
   656  		return nil
   657  	}
   658  	n := (1 + re.numSubexp) * 2
   659  	for len(a) < n {
   660  		a = append(a, -1)
   661  	}
   662  	return a
   663  }
   664  
   665  // Find matches in slice b if b is non-nil, otherwise find matches in string s.
   666  func (re *Regexp) allMatches(s string, b []byte, n int, deliver func([]int)) {
   667  	var end int
   668  	if b == nil {
   669  		end = len(s)
   670  	} else {
   671  		end = len(b)
   672  	}
   673  
   674  	for pos, i, prevMatchEnd := 0, 0, -1; i < n && pos <= end; {
   675  		matches := re.doExecute(nil, b, s, pos, re.prog.NumCap, nil)
   676  		if len(matches) == 0 {
   677  			break
   678  		}
   679  
   680  		accept := true
   681  		if matches[1] == pos {
   682  			// We've found an empty match.
   683  			if matches[0] == prevMatchEnd {
   684  				// We don't allow an empty match right
   685  				// after a previous match, so ignore it.
   686  				accept = false
   687  			}
   688  			var width int
   689  			// TODO: use step()
   690  			if b == nil {
   691  				_, width = utf8.DecodeRuneInString(s[pos:end])
   692  			} else {
   693  				_, width = utf8.DecodeRune(b[pos:end])
   694  			}
   695  			if width > 0 {
   696  				pos += width
   697  			} else {
   698  				pos = end + 1
   699  			}
   700  		} else {
   701  			pos = matches[1]
   702  		}
   703  		prevMatchEnd = matches[1]
   704  
   705  		if accept {
   706  			deliver(re.pad(matches))
   707  			i++
   708  		}
   709  	}
   710  }
   711  
   712  // Find returns a slice holding the text of the leftmost match in b of the regular expression.
   713  // A return value of nil indicates no match.
   714  func (re *Regexp) Find(b []byte) []byte {
   715  	var dstCap [2]int
   716  	a := re.doExecute(nil, b, "", 0, 2, dstCap[:0])
   717  	if a == nil {
   718  		return nil
   719  	}
   720  	return b[a[0]:a[1]]
   721  }
   722  
   723  // FindIndex returns a two-element slice of integers defining the location of
   724  // the leftmost match in b of the regular expression. The match itself is at
   725  // b[loc[0]:loc[1]].
   726  // A return value of nil indicates no match.
   727  func (re *Regexp) FindIndex(b []byte) (loc []int) {
   728  	a := re.doExecute(nil, b, "", 0, 2, nil)
   729  	if a == nil {
   730  		return nil
   731  	}
   732  	return a[0:2]
   733  }
   734  
   735  // FindString returns a string holding the text of the leftmost match in s of the regular
   736  // expression. If there is no match, the return value is an empty string,
   737  // but it will also be empty if the regular expression successfully matches
   738  // an empty string. Use FindStringIndex or FindStringSubmatch if it is
   739  // necessary to distinguish these cases.
   740  func (re *Regexp) FindString(s string) string {
   741  	var dstCap [2]int
   742  	a := re.doExecute(nil, nil, s, 0, 2, dstCap[:0])
   743  	if a == nil {
   744  		return ""
   745  	}
   746  	return s[a[0]:a[1]]
   747  }
   748  
   749  // FindStringIndex returns a two-element slice of integers defining the
   750  // location of the leftmost match in s of the regular expression. The match
   751  // itself is at s[loc[0]:loc[1]].
   752  // A return value of nil indicates no match.
   753  func (re *Regexp) FindStringIndex(s string) (loc []int) {
   754  	a := re.doExecute(nil, nil, s, 0, 2, nil)
   755  	if a == nil {
   756  		return nil
   757  	}
   758  	return a[0:2]
   759  }
   760  
   761  // FindReaderIndex returns a two-element slice of integers defining the
   762  // location of the leftmost match of the regular expression in text read from
   763  // the RuneReader. The match text was found in the input stream at
   764  // byte offset loc[0] through loc[1]-1.
   765  // A return value of nil indicates no match.
   766  func (re *Regexp) FindReaderIndex(r io.RuneReader) (loc []int) {
   767  	a := re.doExecute(r, nil, "", 0, 2, nil)
   768  	if a == nil {
   769  		return nil
   770  	}
   771  	return a[0:2]
   772  }
   773  
   774  // FindSubmatch returns a slice of slices holding the text of the leftmost
   775  // match of the regular expression in b and the matches, if any, of its
   776  // subexpressions, as defined by the 'Submatch' descriptions in the package
   777  // comment.
   778  // A return value of nil indicates no match.
   779  func (re *Regexp) FindSubmatch(b []byte) [][]byte {
   780  	var dstCap [4]int
   781  	a := re.doExecute(nil, b, "", 0, re.prog.NumCap, dstCap[:0])
   782  	if a == nil {
   783  		return nil
   784  	}
   785  	ret := make([][]byte, 1+re.numSubexp)
   786  	for i := range ret {
   787  		if 2*i < len(a) && a[2*i] >= 0 {
   788  			ret[i] = b[a[2*i]:a[2*i+1]]
   789  		}
   790  	}
   791  	return ret
   792  }
   793  
   794  // Expand appends template to dst and returns the result; during the
   795  // append, Expand replaces variables in the template with corresponding
   796  // matches drawn from src. The match slice should have been returned by
   797  // FindSubmatchIndex.
   798  //
   799  // In the template, a variable is denoted by a substring of the form
   800  // $name or ${name}, where name is a non-empty sequence of letters,
   801  // digits, and underscores. A purely numeric name like $1 refers to
   802  // the submatch with the corresponding index; other names refer to
   803  // capturing parentheses named with the (?P<name>...) syntax. A
   804  // reference to an out of range or unmatched index or a name that is not
   805  // present in the regular expression is replaced with an empty slice.
   806  //
   807  // In the $name form, name is taken to be as long as possible: $1x is
   808  // equivalent to ${1x}, not ${1}x, and, $10 is equivalent to ${10}, not ${1}0.
   809  //
   810  // To insert a literal $ in the output, use $$ in the template.
   811  func (re *Regexp) Expand(dst []byte, template []byte, src []byte, match []int) []byte {
   812  	return re.expand(dst, string(template), src, "", match)
   813  }
   814  
   815  // ExpandString is like Expand but the template and source are strings.
   816  // It appends to and returns a byte slice in order to give the calling
   817  // code control over allocation.
   818  func (re *Regexp) ExpandString(dst []byte, template string, src string, match []int) []byte {
   819  	return re.expand(dst, template, nil, src, match)
   820  }
   821  
   822  func (re *Regexp) expand(dst []byte, template string, bsrc []byte, src string, match []int) []byte {
   823  	for len(template) > 0 {
   824  		i := strings.Index(template, "$")
   825  		if i < 0 {
   826  			break
   827  		}
   828  		dst = append(dst, template[:i]...)
   829  		template = template[i:]
   830  		if len(template) > 1 && template[1] == '$' {
   831  			// Treat $$ as $.
   832  			dst = append(dst, '$')
   833  			template = template[2:]
   834  			continue
   835  		}
   836  		name, num, rest, ok := extract(template)
   837  		if !ok {
   838  			// Malformed; treat $ as raw text.
   839  			dst = append(dst, '$')
   840  			template = template[1:]
   841  			continue
   842  		}
   843  		template = rest
   844  		if num >= 0 {
   845  			if 2*num+1 < len(match) && match[2*num] >= 0 {
   846  				if bsrc != nil {
   847  					dst = append(dst, bsrc[match[2*num]:match[2*num+1]]...)
   848  				} else {
   849  					dst = append(dst, src[match[2*num]:match[2*num+1]]...)
   850  				}
   851  			}
   852  		} else {
   853  			for i, namei := range re.subexpNames {
   854  				if name == namei && 2*i+1 < len(match) && match[2*i] >= 0 {
   855  					if bsrc != nil {
   856  						dst = append(dst, bsrc[match[2*i]:match[2*i+1]]...)
   857  					} else {
   858  						dst = append(dst, src[match[2*i]:match[2*i+1]]...)
   859  					}
   860  					break
   861  				}
   862  			}
   863  		}
   864  	}
   865  	dst = append(dst, template...)
   866  	return dst
   867  }
   868  
   869  // extract returns the name from a leading "$name" or "${name}" in str.
   870  // If it is a number, extract returns num set to that number; otherwise num = -1.
   871  func extract(str string) (name string, num int, rest string, ok bool) {
   872  	if len(str) < 2 || str[0] != '$' {
   873  		return
   874  	}
   875  	brace := false
   876  	if str[1] == '{' {
   877  		brace = true
   878  		str = str[2:]
   879  	} else {
   880  		str = str[1:]
   881  	}
   882  	i := 0
   883  	for i < len(str) {
   884  		rune, size := utf8.DecodeRuneInString(str[i:])
   885  		if !unicode.IsLetter(rune) && !unicode.IsDigit(rune) && rune != '_' {
   886  			break
   887  		}
   888  		i += size
   889  	}
   890  	if i == 0 {
   891  		// empty name is not okay
   892  		return
   893  	}
   894  	name = str[:i]
   895  	if brace {
   896  		if i >= len(str) || str[i] != '}' {
   897  			// missing closing brace
   898  			return
   899  		}
   900  		i++
   901  	}
   902  
   903  	// Parse number.
   904  	num = 0
   905  	for i := 0; i < len(name); i++ {
   906  		if name[i] < '0' || '9' < name[i] || num >= 1e8 {
   907  			num = -1
   908  			break
   909  		}
   910  		num = num*10 + int(name[i]) - '0'
   911  	}
   912  	// Disallow leading zeros.
   913  	if name[0] == '0' && len(name) > 1 {
   914  		num = -1
   915  	}
   916  
   917  	rest = str[i:]
   918  	ok = true
   919  	return
   920  }
   921  
   922  // FindSubmatchIndex returns a slice holding the index pairs identifying the
   923  // leftmost match of the regular expression in b and the matches, if any, of
   924  // its subexpressions, as defined by the 'Submatch' and 'Index' descriptions
   925  // in the package comment.
   926  // A return value of nil indicates no match.
   927  func (re *Regexp) FindSubmatchIndex(b []byte) []int {
   928  	return re.pad(re.doExecute(nil, b, "", 0, re.prog.NumCap, nil))
   929  }
   930  
   931  // FindStringSubmatch returns a slice of strings holding the text of the
   932  // leftmost match of the regular expression in s and the matches, if any, of
   933  // its subexpressions, as defined by the 'Submatch' description in the
   934  // package comment.
   935  // A return value of nil indicates no match.
   936  func (re *Regexp) FindStringSubmatch(s string) []string {
   937  	var dstCap [4]int
   938  	a := re.doExecute(nil, nil, s, 0, re.prog.NumCap, dstCap[:0])
   939  	if a == nil {
   940  		return nil
   941  	}
   942  	ret := make([]string, 1+re.numSubexp)
   943  	for i := range ret {
   944  		if 2*i < len(a) && a[2*i] >= 0 {
   945  			ret[i] = s[a[2*i]:a[2*i+1]]
   946  		}
   947  	}
   948  	return ret
   949  }
   950  
   951  // FindStringSubmatchIndex returns a slice holding the index pairs
   952  // identifying the leftmost match of the regular expression in s and the
   953  // matches, if any, of its subexpressions, as defined by the 'Submatch' and
   954  // 'Index' descriptions in the package comment.
   955  // A return value of nil indicates no match.
   956  func (re *Regexp) FindStringSubmatchIndex(s string) []int {
   957  	return re.pad(re.doExecute(nil, nil, s, 0, re.prog.NumCap, nil))
   958  }
   959  
   960  // FindReaderSubmatchIndex returns a slice holding the index pairs
   961  // identifying the leftmost match of the regular expression of text read by
   962  // the RuneReader, and the matches, if any, of its subexpressions, as defined
   963  // by the 'Submatch' and 'Index' descriptions in the package comment. A
   964  // return value of nil indicates no match.
   965  func (re *Regexp) FindReaderSubmatchIndex(r io.RuneReader) []int {
   966  	return re.pad(re.doExecute(r, nil, "", 0, re.prog.NumCap, nil))
   967  }
   968  
   969  const startSize = 10 // The size at which to start a slice in the 'All' routines.
   970  
   971  // FindAll is the 'All' version of Find; it returns a slice of all successive
   972  // matches of the expression, as defined by the 'All' description in the
   973  // package comment.
   974  // A return value of nil indicates no match.
   975  func (re *Regexp) FindAll(b []byte, n int) [][]byte {
   976  	if n < 0 {
   977  		n = len(b) + 1
   978  	}
   979  	result := make([][]byte, 0, startSize)
   980  	re.allMatches("", b, n, func(match []int) {
   981  		result = append(result, b[match[0]:match[1]])
   982  	})
   983  	if len(result) == 0 {
   984  		return nil
   985  	}
   986  	return result
   987  }
   988  
   989  // FindAllIndex is the 'All' version of FindIndex; it returns a slice of all
   990  // successive matches of the expression, as defined by the 'All' description
   991  // in the package comment.
   992  // A return value of nil indicates no match.
   993  func (re *Regexp) FindAllIndex(b []byte, n int) [][]int {
   994  	if n < 0 {
   995  		n = len(b) + 1
   996  	}
   997  	result := make([][]int, 0, startSize)
   998  	re.allMatches("", b, n, func(match []int) {
   999  		result = append(result, match[0:2])
  1000  	})
  1001  	if len(result) == 0 {
  1002  		return nil
  1003  	}
  1004  	return result
  1005  }
  1006  
  1007  // FindAllString is the 'All' version of FindString; it returns a slice of all
  1008  // successive matches of the expression, as defined by the 'All' description
  1009  // in the package comment.
  1010  // A return value of nil indicates no match.
  1011  func (re *Regexp) FindAllString(s string, n int) []string {
  1012  	if n < 0 {
  1013  		n = len(s) + 1
  1014  	}
  1015  	result := make([]string, 0, startSize)
  1016  	re.allMatches(s, nil, n, func(match []int) {
  1017  		result = append(result, s[match[0]:match[1]])
  1018  	})
  1019  	if len(result) == 0 {
  1020  		return nil
  1021  	}
  1022  	return result
  1023  }
  1024  
  1025  // FindAllStringIndex is the 'All' version of FindStringIndex; it returns a
  1026  // slice of all successive matches of the expression, as defined by the 'All'
  1027  // description in the package comment.
  1028  // A return value of nil indicates no match.
  1029  func (re *Regexp) FindAllStringIndex(s string, n int) [][]int {
  1030  	if n < 0 {
  1031  		n = len(s) + 1
  1032  	}
  1033  	result := make([][]int, 0, startSize)
  1034  	re.allMatches(s, nil, n, func(match []int) {
  1035  		result = append(result, match[0:2])
  1036  	})
  1037  	if len(result) == 0 {
  1038  		return nil
  1039  	}
  1040  	return result
  1041  }
  1042  
  1043  // FindAllSubmatch is the 'All' version of FindSubmatch; it returns a slice
  1044  // of all successive matches of the expression, as defined by the 'All'
  1045  // description in the package comment.
  1046  // A return value of nil indicates no match.
  1047  func (re *Regexp) FindAllSubmatch(b []byte, n int) [][][]byte {
  1048  	if n < 0 {
  1049  		n = len(b) + 1
  1050  	}
  1051  	result := make([][][]byte, 0, startSize)
  1052  	re.allMatches("", b, n, func(match []int) {
  1053  		slice := make([][]byte, len(match)/2)
  1054  		for j := range slice {
  1055  			if match[2*j] >= 0 {
  1056  				slice[j] = b[match[2*j]:match[2*j+1]]
  1057  			}
  1058  		}
  1059  		result = append(result, slice)
  1060  	})
  1061  	if len(result) == 0 {
  1062  		return nil
  1063  	}
  1064  	return result
  1065  }
  1066  
  1067  // FindAllSubmatchIndex is the 'All' version of FindSubmatchIndex; it returns
  1068  // a slice of all successive matches of the expression, as defined by the
  1069  // 'All' description in the package comment.
  1070  // A return value of nil indicates no match.
  1071  func (re *Regexp) FindAllSubmatchIndex(b []byte, n int) [][]int {
  1072  	if n < 0 {
  1073  		n = len(b) + 1
  1074  	}
  1075  	result := make([][]int, 0, startSize)
  1076  	re.allMatches("", b, n, func(match []int) {
  1077  		result = append(result, match)
  1078  	})
  1079  	if len(result) == 0 {
  1080  		return nil
  1081  	}
  1082  	return result
  1083  }
  1084  
  1085  // FindAllStringSubmatch is the 'All' version of FindStringSubmatch; it
  1086  // returns a slice of all successive matches of the expression, as defined by
  1087  // the 'All' description in the package comment.
  1088  // A return value of nil indicates no match.
  1089  func (re *Regexp) FindAllStringSubmatch(s string, n int) [][]string {
  1090  	if n < 0 {
  1091  		n = len(s) + 1
  1092  	}
  1093  	result := make([][]string, 0, startSize)
  1094  	re.allMatches(s, nil, n, func(match []int) {
  1095  		slice := make([]string, len(match)/2)
  1096  		for j := range slice {
  1097  			if match[2*j] >= 0 {
  1098  				slice[j] = s[match[2*j]:match[2*j+1]]
  1099  			}
  1100  		}
  1101  		result = append(result, slice)
  1102  	})
  1103  	if len(result) == 0 {
  1104  		return nil
  1105  	}
  1106  	return result
  1107  }
  1108  
  1109  // FindAllStringSubmatchIndex is the 'All' version of
  1110  // FindStringSubmatchIndex; it returns a slice of all successive matches of
  1111  // the expression, as defined by the 'All' description in the package
  1112  // comment.
  1113  // A return value of nil indicates no match.
  1114  func (re *Regexp) FindAllStringSubmatchIndex(s string, n int) [][]int {
  1115  	if n < 0 {
  1116  		n = len(s) + 1
  1117  	}
  1118  	result := make([][]int, 0, startSize)
  1119  	re.allMatches(s, nil, n, func(match []int) {
  1120  		result = append(result, match)
  1121  	})
  1122  	if len(result) == 0 {
  1123  		return nil
  1124  	}
  1125  	return result
  1126  }
  1127  
  1128  // Split slices s into substrings separated by the expression and returns a slice of
  1129  // the substrings between those expression matches.
  1130  //
  1131  // The slice returned by this method consists of all the substrings of s
  1132  // not contained in the slice returned by FindAllString. When called on an expression
  1133  // that contains no metacharacters, it is equivalent to strings.SplitN.
  1134  //
  1135  // Example:
  1136  //   s := regexp.MustCompile("a*").Split("abaabaccadaaae", 5)
  1137  //   // s: ["", "b", "b", "c", "cadaaae"]
  1138  //
  1139  // The count determines the number of substrings to return:
  1140  //   n > 0: at most n substrings; the last substring will be the unsplit remainder.
  1141  //   n == 0: the result is nil (zero substrings)
  1142  //   n < 0: all substrings
  1143  func (re *Regexp) Split(s string, n int) []string {
  1144  
  1145  	if n == 0 {
  1146  		return nil
  1147  	}
  1148  
  1149  	if len(re.expr) > 0 && len(s) == 0 {
  1150  		return []string{""}
  1151  	}
  1152  
  1153  	matches := re.FindAllStringIndex(s, n)
  1154  	strings := make([]string, 0, len(matches))
  1155  
  1156  	beg := 0
  1157  	end := 0
  1158  	for _, match := range matches {
  1159  		if n > 0 && len(strings) >= n-1 {
  1160  			break
  1161  		}
  1162  
  1163  		end = match[0]
  1164  		if match[1] != 0 {
  1165  			strings = append(strings, s[beg:end])
  1166  		}
  1167  		beg = match[1]
  1168  	}
  1169  
  1170  	if end != len(s) {
  1171  		strings = append(strings, s[beg:])
  1172  	}
  1173  
  1174  	return strings
  1175  }