Source file src/regexp/example_test.go

     1  // Copyright 2013 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_test
     6  
     7  import (
     8  	"fmt"
     9  	"regexp"
    10  	"strings"
    11  )
    12  
    13  func Example() {
    14  	// Compile the expression once, usually at init time.
    15  	// Use raw strings to avoid having to quote the backslashes.
    16  	var validID = regexp.MustCompile(`^[a-z]+\[[0-9]+\]$`)
    17  
    18  	fmt.Println(validID.MatchString("adam[23]"))
    19  	fmt.Println(validID.MatchString("eve[7]"))
    20  	fmt.Println(validID.MatchString("Job[48]"))
    21  	fmt.Println(validID.MatchString("snakey"))
    22  	// Output:
    23  	// true
    24  	// true
    25  	// false
    26  	// false
    27  }
    28  
    29  func ExampleMatch() {
    30  	matched, err := regexp.Match(`foo.*`, []byte(`seafood`))
    31  	fmt.Println(matched, err)
    32  	matched, err = regexp.Match(`bar.*`, []byte(`seafood`))
    33  	fmt.Println(matched, err)
    34  	matched, err = regexp.Match(`a(b`, []byte(`seafood`))
    35  	fmt.Println(matched, err)
    36  
    37  	// Output:
    38  	// true <nil>
    39  	// false <nil>
    40  	// false error parsing regexp: missing closing ): `a(b`
    41  }
    42  
    43  func ExampleMatchString() {
    44  	matched, err := regexp.MatchString(`foo.*`, "seafood")
    45  	fmt.Println(matched, err)
    46  	matched, err = regexp.MatchString(`bar.*`, "seafood")
    47  	fmt.Println(matched, err)
    48  	matched, err = regexp.MatchString(`a(b`, "seafood")
    49  	fmt.Println(matched, err)
    50  	// Output:
    51  	// true <nil>
    52  	// false <nil>
    53  	// false error parsing regexp: missing closing ): `a(b`
    54  }
    55  
    56  func ExampleQuoteMeta() {
    57  	fmt.Println(regexp.QuoteMeta(`Escaping symbols like: .+*?()|[]{}^$`))
    58  	// Output:
    59  	// Escaping symbols like: \.\+\*\?\(\)\|\[\]\{\}\^\$
    60  }
    61  
    62  func ExampleRegexp_Find() {
    63  	re := regexp.MustCompile(`foo.?`)
    64  	fmt.Printf("%q\n", re.Find([]byte(`seafood fool`)))
    65  
    66  	// Output:
    67  	// "food"
    68  }
    69  
    70  func ExampleRegexp_FindAll() {
    71  	re := regexp.MustCompile(`foo.?`)
    72  	fmt.Printf("%q\n", re.FindAll([]byte(`seafood fool`), -1))
    73  
    74  	// Output:
    75  	// ["food" "fool"]
    76  }
    77  
    78  func ExampleRegexp_FindAllSubmatch() {
    79  	re := regexp.MustCompile(`foo(.?)`)
    80  	fmt.Printf("%q\n", re.FindAllSubmatch([]byte(`seafood fool`), -1))
    81  
    82  	// Output:
    83  	// [["food" "d"] ["fool" "l"]]
    84  }
    85  
    86  func ExampleRegexp_FindSubmatch() {
    87  	re := regexp.MustCompile(`foo(.?)`)
    88  	fmt.Printf("%q\n", re.FindSubmatch([]byte(`seafood fool`)))
    89  
    90  	// Output:
    91  	// ["food" "d"]
    92  }
    93  
    94  func ExampleRegexp_Match() {
    95  	re := regexp.MustCompile(`foo.?`)
    96  	fmt.Println(re.Match([]byte(`seafood fool`)))
    97  	fmt.Println(re.Match([]byte(`something else`)))
    98  
    99  	// Output:
   100  	// true
   101  	// false
   102  }
   103  
   104  func ExampleRegexp_FindString() {
   105  	re := regexp.MustCompile(`foo.?`)
   106  	fmt.Printf("%q\n", re.FindString("seafood fool"))
   107  	fmt.Printf("%q\n", re.FindString("meat"))
   108  	// Output:
   109  	// "food"
   110  	// ""
   111  }
   112  
   113  func ExampleRegexp_FindStringIndex() {
   114  	re := regexp.MustCompile(`ab?`)
   115  	fmt.Println(re.FindStringIndex("tablett"))
   116  	fmt.Println(re.FindStringIndex("foo") == nil)
   117  	// Output:
   118  	// [1 3]
   119  	// true
   120  }
   121  
   122  func ExampleRegexp_FindStringSubmatch() {
   123  	re := regexp.MustCompile(`a(x*)b(y|z)c`)
   124  	fmt.Printf("%q\n", re.FindStringSubmatch("-axxxbyc-"))
   125  	fmt.Printf("%q\n", re.FindStringSubmatch("-abzc-"))
   126  	// Output:
   127  	// ["axxxbyc" "xxx" "y"]
   128  	// ["abzc" "" "z"]
   129  }
   130  
   131  func ExampleRegexp_FindAllString() {
   132  	re := regexp.MustCompile(`a.`)
   133  	fmt.Println(re.FindAllString("paranormal", -1))
   134  	fmt.Println(re.FindAllString("paranormal", 2))
   135  	fmt.Println(re.FindAllString("graal", -1))
   136  	fmt.Println(re.FindAllString("none", -1))
   137  	// Output:
   138  	// [ar an al]
   139  	// [ar an]
   140  	// [aa]
   141  	// []
   142  }
   143  
   144  func ExampleRegexp_FindAllStringSubmatch() {
   145  	re := regexp.MustCompile(`a(x*)b`)
   146  	fmt.Printf("%q\n", re.FindAllStringSubmatch("-ab-", -1))
   147  	fmt.Printf("%q\n", re.FindAllStringSubmatch("-axxb-", -1))
   148  	fmt.Printf("%q\n", re.FindAllStringSubmatch("-ab-axb-", -1))
   149  	fmt.Printf("%q\n", re.FindAllStringSubmatch("-axxb-ab-", -1))
   150  	// Output:
   151  	// [["ab" ""]]
   152  	// [["axxb" "xx"]]
   153  	// [["ab" ""] ["axb" "x"]]
   154  	// [["axxb" "xx"] ["ab" ""]]
   155  }
   156  
   157  func ExampleRegexp_FindAllStringSubmatchIndex() {
   158  	re := regexp.MustCompile(`a(x*)b`)
   159  	// Indices:
   160  	//    01234567   012345678
   161  	//    -ab-axb-   -axxb-ab-
   162  	fmt.Println(re.FindAllStringSubmatchIndex("-ab-", -1))
   163  	fmt.Println(re.FindAllStringSubmatchIndex("-axxb-", -1))
   164  	fmt.Println(re.FindAllStringSubmatchIndex("-ab-axb-", -1))
   165  	fmt.Println(re.FindAllStringSubmatchIndex("-axxb-ab-", -1))
   166  	fmt.Println(re.FindAllStringSubmatchIndex("-foo-", -1))
   167  	// Output:
   168  	// [[1 3 2 2]]
   169  	// [[1 5 2 4]]
   170  	// [[1 3 2 2] [4 7 5 6]]
   171  	// [[1 5 2 4] [6 8 7 7]]
   172  	// []
   173  }
   174  
   175  func ExampleRegexp_FindSubmatchIndex() {
   176  	re := regexp.MustCompile(`a(x*)b`)
   177  	// Indices:
   178  	//    01234567   012345678
   179  	//    -ab-axb-   -axxb-ab-
   180  	fmt.Println(re.FindSubmatchIndex([]byte("-ab-")))
   181  	fmt.Println(re.FindSubmatchIndex([]byte("-axxb-")))
   182  	fmt.Println(re.FindSubmatchIndex([]byte("-ab-axb-")))
   183  	fmt.Println(re.FindSubmatchIndex([]byte("-axxb-ab-")))
   184  	fmt.Println(re.FindSubmatchIndex([]byte("-foo-")))
   185  	// Output:
   186  	// [1 3 2 2]
   187  	// [1 5 2 4]
   188  	// [1 3 2 2]
   189  	// [1 5 2 4]
   190  	// []
   191  }
   192  
   193  func ExampleRegexp_Longest() {
   194  	re := regexp.MustCompile(`a(|b)`)
   195  	fmt.Println(re.FindString("ab"))
   196  	re.Longest()
   197  	fmt.Println(re.FindString("ab"))
   198  	// Output:
   199  	// a
   200  	// ab
   201  }
   202  
   203  func ExampleRegexp_MatchString() {
   204  	re := regexp.MustCompile(`(gopher){2}`)
   205  	fmt.Println(re.MatchString("gopher"))
   206  	fmt.Println(re.MatchString("gophergopher"))
   207  	fmt.Println(re.MatchString("gophergophergopher"))
   208  	// Output:
   209  	// false
   210  	// true
   211  	// true
   212  }
   213  
   214  func ExampleRegexp_NumSubexp() {
   215  	re0 := regexp.MustCompile(`a.`)
   216  	fmt.Printf("%d\n", re0.NumSubexp())
   217  
   218  	re := regexp.MustCompile(`(.*)((a)b)(.*)a`)
   219  	fmt.Println(re.NumSubexp())
   220  	// Output:
   221  	// 0
   222  	// 4
   223  }
   224  
   225  func ExampleRegexp_ReplaceAll() {
   226  	re := regexp.MustCompile(`a(x*)b`)
   227  	fmt.Printf("%s\n", re.ReplaceAll([]byte("-ab-axxb-"), []byte("T")))
   228  	fmt.Printf("%s\n", re.ReplaceAll([]byte("-ab-axxb-"), []byte("$1")))
   229  	fmt.Printf("%s\n", re.ReplaceAll([]byte("-ab-axxb-"), []byte("$1W")))
   230  	fmt.Printf("%s\n", re.ReplaceAll([]byte("-ab-axxb-"), []byte("${1}W")))
   231  	// Output:
   232  	// -T-T-
   233  	// --xx-
   234  	// ---
   235  	// -W-xxW-
   236  }
   237  
   238  func ExampleRegexp_ReplaceAllLiteralString() {
   239  	re := regexp.MustCompile(`a(x*)b`)
   240  	fmt.Println(re.ReplaceAllLiteralString("-ab-axxb-", "T"))
   241  	fmt.Println(re.ReplaceAllLiteralString("-ab-axxb-", "$1"))
   242  	fmt.Println(re.ReplaceAllLiteralString("-ab-axxb-", "${1}"))
   243  	// Output:
   244  	// -T-T-
   245  	// -$1-$1-
   246  	// -${1}-${1}-
   247  }
   248  
   249  func ExampleRegexp_ReplaceAllString() {
   250  	re := regexp.MustCompile(`a(x*)b`)
   251  	fmt.Println(re.ReplaceAllString("-ab-axxb-", "T"))
   252  	fmt.Println(re.ReplaceAllString("-ab-axxb-", "$1"))
   253  	fmt.Println(re.ReplaceAllString("-ab-axxb-", "$1W"))
   254  	fmt.Println(re.ReplaceAllString("-ab-axxb-", "${1}W"))
   255  	// Output:
   256  	// -T-T-
   257  	// --xx-
   258  	// ---
   259  	// -W-xxW-
   260  }
   261  
   262  func ExampleRegexp_ReplaceAllStringFunc() {
   263  	re := regexp.MustCompile(`[^aeiou]`)
   264  	fmt.Println(re.ReplaceAllStringFunc("seafood fool", strings.ToUpper))
   265  	// Output:
   266  	// SeaFooD FooL
   267  }
   268  
   269  func ExampleRegexp_SubexpNames() {
   270  	re := regexp.MustCompile(`(?P<first>[a-zA-Z]+) (?P<last>[a-zA-Z]+)`)
   271  	fmt.Println(re.MatchString("Alan Turing"))
   272  	fmt.Printf("%q\n", re.SubexpNames())
   273  	reversed := fmt.Sprintf("${%s} ${%s}", re.SubexpNames()[2], re.SubexpNames()[1])
   274  	fmt.Println(reversed)
   275  	fmt.Println(re.ReplaceAllString("Alan Turing", reversed))
   276  	// Output:
   277  	// true
   278  	// ["" "first" "last"]
   279  	// ${last} ${first}
   280  	// Turing Alan
   281  }
   282  
   283  func ExampleRegexp_SubexpIndex() {
   284  	re := regexp.MustCompile(`(?P<first>[a-zA-Z]+) (?P<last>[a-zA-Z]+)`)
   285  	fmt.Println(re.MatchString("Alan Turing"))
   286  	matches := re.FindStringSubmatch("Alan Turing")
   287  	lastIndex := re.SubexpIndex("last")
   288  	fmt.Printf("last => %d\n", lastIndex)
   289  	fmt.Println(matches[lastIndex])
   290  	// Output:
   291  	// true
   292  	// last => 2
   293  	// Turing
   294  }
   295  
   296  func ExampleRegexp_Split() {
   297  	a := regexp.MustCompile(`a`)
   298  	fmt.Println(a.Split("banana", -1))
   299  	fmt.Println(a.Split("banana", 0))
   300  	fmt.Println(a.Split("banana", 1))
   301  	fmt.Println(a.Split("banana", 2))
   302  	zp := regexp.MustCompile(`z+`)
   303  	fmt.Println(zp.Split("pizza", -1))
   304  	fmt.Println(zp.Split("pizza", 0))
   305  	fmt.Println(zp.Split("pizza", 1))
   306  	fmt.Println(zp.Split("pizza", 2))
   307  	// Output:
   308  	// [b n n ]
   309  	// []
   310  	// [banana]
   311  	// [b nana]
   312  	// [pi a]
   313  	// []
   314  	// [pizza]
   315  	// [pi a]
   316  }
   317  
   318  func ExampleRegexp_Expand() {
   319  	content := []byte(`
   320  	# comment line
   321  	option1: value1
   322  	option2: value2
   323  
   324  	# another comment line
   325  	option3: value3
   326  `)
   327  
   328  	// Regex pattern captures "key: value" pair from the content.
   329  	pattern := regexp.MustCompile(`(?m)(?P<key>\w+):\s+(?P<value>\w+)$`)
   330  
   331  	// Template to convert "key: value" to "key=value" by
   332  	// referencing the values captured by the regex pattern.
   333  	template := []byte("$key=$value\n")
   334  
   335  	result := []byte{}
   336  
   337  	// For each match of the regex in the content.
   338  	for _, submatches := range pattern.FindAllSubmatchIndex(content, -1) {
   339  		// Apply the captured submatches to the template and append the output
   340  		// to the result.
   341  		result = pattern.Expand(result, template, content, submatches)
   342  	}
   343  	fmt.Println(string(result))
   344  	// Output:
   345  	// option1=value1
   346  	// option2=value2
   347  	// option3=value3
   348  }
   349  
   350  func ExampleRegexp_ExpandString() {
   351  	content := `
   352  	# comment line
   353  	option1: value1
   354  	option2: value2
   355  
   356  	# another comment line
   357  	option3: value3
   358  `
   359  
   360  	// Regex pattern captures "key: value" pair from the content.
   361  	pattern := regexp.MustCompile(`(?m)(?P<key>\w+):\s+(?P<value>\w+)$`)
   362  
   363  	// Template to convert "key: value" to "key=value" by
   364  	// referencing the values captured by the regex pattern.
   365  	template := "$key=$value\n"
   366  
   367  	result := []byte{}
   368  
   369  	// For each match of the regex in the content.
   370  	for _, submatches := range pattern.FindAllStringSubmatchIndex(content, -1) {
   371  		// Apply the captured submatches to the template and append the output
   372  		// to the result.
   373  		result = pattern.ExpandString(result, template, content, submatches)
   374  	}
   375  	fmt.Println(string(result))
   376  	// Output:
   377  	// option1=value1
   378  	// option2=value2
   379  	// option3=value3
   380  }
   381  
   382  func ExampleRegexp_FindIndex() {
   383  	content := []byte(`
   384  	# comment line
   385  	option1: value1
   386  	option2: value2
   387  `)
   388  	// Regex pattern captures "key: value" pair from the content.
   389  	pattern := regexp.MustCompile(`(?m)(?P<key>\w+):\s+(?P<value>\w+)$`)
   390  
   391  	loc := pattern.FindIndex(content)
   392  	fmt.Println(loc)
   393  	fmt.Println(string(content[loc[0]:loc[1]]))
   394  	// Output:
   395  	// [18 33]
   396  	// option1: value1
   397  }
   398  
   399  func ExampleRegexp_FindAllSubmatchIndex() {
   400  	content := []byte(`
   401  	# comment line
   402  	option1: value1
   403  	option2: value2
   404  `)
   405  	// Regex pattern captures "key: value" pair from the content.
   406  	pattern := regexp.MustCompile(`(?m)(?P<key>\w+):\s+(?P<value>\w+)$`)
   407  	allIndexes := pattern.FindAllSubmatchIndex(content, -1)
   408  	for _, loc := range allIndexes {
   409  		fmt.Println(loc)
   410  		fmt.Println(string(content[loc[0]:loc[1]]))
   411  		fmt.Println(string(content[loc[2]:loc[3]]))
   412  		fmt.Println(string(content[loc[4]:loc[5]]))
   413  	}
   414  	// Output:
   415  	// [18 33 18 25 27 33]
   416  	// option1: value1
   417  	// option1
   418  	// value1
   419  	// [35 50 35 42 44 50]
   420  	// option2: value2
   421  	// option2
   422  	// value2
   423  }
   424  
   425  func ExampleRegexp_FindAllIndex() {
   426  	content := []byte("London")
   427  	re := regexp.MustCompile(`o.`)
   428  	fmt.Println(re.FindAllIndex(content, 1))
   429  	fmt.Println(re.FindAllIndex(content, -1))
   430  	// Output:
   431  	// [[1 3]]
   432  	// [[1 3] [4 6]]
   433  }
   434  

View as plain text