Home | History | Annotate | Download | only in regexp
      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 )
     11 
     12 func Example() {
     13 	// Compile the expression once, usually at init time.
     14 	// Use raw strings to avoid having to quote the backslashes.
     15 	var validID = regexp.MustCompile(`^[a-z]+\[[0-9]+\]$`)
     16 
     17 	fmt.Println(validID.MatchString("adam[23]"))
     18 	fmt.Println(validID.MatchString("eve[7]"))
     19 	fmt.Println(validID.MatchString("Job[48]"))
     20 	fmt.Println(validID.MatchString("snakey"))
     21 	// Output:
     22 	// true
     23 	// true
     24 	// false
     25 	// false
     26 }
     27 
     28 func ExampleMatchString() {
     29 	matched, err := regexp.MatchString("foo.*", "seafood")
     30 	fmt.Println(matched, err)
     31 	matched, err = regexp.MatchString("bar.*", "seafood")
     32 	fmt.Println(matched, err)
     33 	matched, err = regexp.MatchString("a(b", "seafood")
     34 	fmt.Println(matched, err)
     35 	// Output:
     36 	// true <nil>
     37 	// false <nil>
     38 	// false error parsing regexp: missing closing ): `a(b`
     39 }
     40 
     41 func ExampleRegexp_FindString() {
     42 	re := regexp.MustCompile("foo.?")
     43 	fmt.Printf("%q\n", re.FindString("seafood fool"))
     44 	fmt.Printf("%q\n", re.FindString("meat"))
     45 	// Output:
     46 	// "food"
     47 	// ""
     48 }
     49 
     50 func ExampleRegexp_FindStringIndex() {
     51 	re := regexp.MustCompile("ab?")
     52 	fmt.Println(re.FindStringIndex("tablett"))
     53 	fmt.Println(re.FindStringIndex("foo") == nil)
     54 	// Output:
     55 	// [1 3]
     56 	// true
     57 }
     58 
     59 func ExampleRegexp_FindStringSubmatch() {
     60 	re := regexp.MustCompile("a(x*)b(y|z)c")
     61 	fmt.Printf("%q\n", re.FindStringSubmatch("-axxxbyc-"))
     62 	fmt.Printf("%q\n", re.FindStringSubmatch("-abzc-"))
     63 	// Output:
     64 	// ["axxxbyc" "xxx" "y"]
     65 	// ["abzc" "" "z"]
     66 }
     67 
     68 func ExampleRegexp_FindAllString() {
     69 	re := regexp.MustCompile("a.")
     70 	fmt.Println(re.FindAllString("paranormal", -1))
     71 	fmt.Println(re.FindAllString("paranormal", 2))
     72 	fmt.Println(re.FindAllString("graal", -1))
     73 	fmt.Println(re.FindAllString("none", -1))
     74 	// Output:
     75 	// [ar an al]
     76 	// [ar an]
     77 	// [aa]
     78 	// []
     79 }
     80 
     81 func ExampleRegexp_FindAllStringSubmatch() {
     82 	re := regexp.MustCompile("a(x*)b")
     83 	fmt.Printf("%q\n", re.FindAllStringSubmatch("-ab-", -1))
     84 	fmt.Printf("%q\n", re.FindAllStringSubmatch("-axxb-", -1))
     85 	fmt.Printf("%q\n", re.FindAllStringSubmatch("-ab-axb-", -1))
     86 	fmt.Printf("%q\n", re.FindAllStringSubmatch("-axxb-ab-", -1))
     87 	// Output:
     88 	// [["ab" ""]]
     89 	// [["axxb" "xx"]]
     90 	// [["ab" ""] ["axb" "x"]]
     91 	// [["axxb" "xx"] ["ab" ""]]
     92 }
     93 
     94 func ExampleRegexp_FindAllStringSubmatchIndex() {
     95 	re := regexp.MustCompile("a(x*)b")
     96 	// Indices:
     97 	//    01234567   012345678
     98 	//    -ab-axb-   -axxb-ab-
     99 	fmt.Println(re.FindAllStringSubmatchIndex("-ab-", -1))
    100 	fmt.Println(re.FindAllStringSubmatchIndex("-axxb-", -1))
    101 	fmt.Println(re.FindAllStringSubmatchIndex("-ab-axb-", -1))
    102 	fmt.Println(re.FindAllStringSubmatchIndex("-axxb-ab-", -1))
    103 	fmt.Println(re.FindAllStringSubmatchIndex("-foo-", -1))
    104 	// Output:
    105 	// [[1 3 2 2]]
    106 	// [[1 5 2 4]]
    107 	// [[1 3 2 2] [4 7 5 6]]
    108 	// [[1 5 2 4] [6 8 7 7]]
    109 	// []
    110 }
    111 
    112 func ExampleRegexp_MatchString() {
    113 	re := regexp.MustCompile("(gopher){2}")
    114 	fmt.Println(re.MatchString("gopher"))
    115 	fmt.Println(re.MatchString("gophergopher"))
    116 	fmt.Println(re.MatchString("gophergophergopher"))
    117 	// Output:
    118 	// false
    119 	// true
    120 	// true
    121 }
    122 
    123 func ExampleRegexp_ReplaceAllLiteralString() {
    124 	re := regexp.MustCompile("a(x*)b")
    125 	fmt.Println(re.ReplaceAllLiteralString("-ab-axxb-", "T"))
    126 	fmt.Println(re.ReplaceAllLiteralString("-ab-axxb-", "$1"))
    127 	fmt.Println(re.ReplaceAllLiteralString("-ab-axxb-", "${1}"))
    128 	// Output:
    129 	// -T-T-
    130 	// -$1-$1-
    131 	// -${1}-${1}-
    132 }
    133 
    134 func ExampleRegexp_ReplaceAllString() {
    135 	re := regexp.MustCompile("a(x*)b")
    136 	fmt.Println(re.ReplaceAllString("-ab-axxb-", "T"))
    137 	fmt.Println(re.ReplaceAllString("-ab-axxb-", "$1"))
    138 	fmt.Println(re.ReplaceAllString("-ab-axxb-", "$1W"))
    139 	fmt.Println(re.ReplaceAllString("-ab-axxb-", "${1}W"))
    140 	// Output:
    141 	// -T-T-
    142 	// --xx-
    143 	// ---
    144 	// -W-xxW-
    145 }
    146 
    147 func ExampleRegexp_SubexpNames() {
    148 	re := regexp.MustCompile("(?P<first>[a-zA-Z]+) (?P<last>[a-zA-Z]+)")
    149 	fmt.Println(re.MatchString("Alan Turing"))
    150 	fmt.Printf("%q\n", re.SubexpNames())
    151 	reversed := fmt.Sprintf("${%s} ${%s}", re.SubexpNames()[2], re.SubexpNames()[1])
    152 	fmt.Println(reversed)
    153 	fmt.Println(re.ReplaceAllString("Alan Turing", reversed))
    154 	// Output:
    155 	// true
    156 	// ["" "first" "last"]
    157 	// ${last} ${first}
    158 	// Turing Alan
    159 }
    160 
    161 func ExampleRegexp_Split() {
    162 	a := regexp.MustCompile("a")
    163 	fmt.Println(a.Split("banana", -1))
    164 	fmt.Println(a.Split("banana", 0))
    165 	fmt.Println(a.Split("banana", 1))
    166 	fmt.Println(a.Split("banana", 2))
    167 	zp := regexp.MustCompile("z+")
    168 	fmt.Println(zp.Split("pizza", -1))
    169 	fmt.Println(zp.Split("pizza", 0))
    170 	fmt.Println(zp.Split("pizza", 1))
    171 	fmt.Println(zp.Split("pizza", 2))
    172 	// Output:
    173 	// [b n n ]
    174 	// []
    175 	// [banana]
    176 	// [b nana]
    177 	// [pi a]
    178 	// []
    179 	// [pizza]
    180 	// [pi a]
    181 }
    182 
    183 func ExampleRegexp_Expand() {
    184 	content := []byte(`
    185 	# comment line
    186 	option1: value1
    187 	option2: value2
    188 
    189 	# another comment line
    190 	option3: value3
    191 `)
    192 
    193 	// Regex pattern captures "key: value" pair from the content.
    194 	pattern := regexp.MustCompile(`(?m)(?P<key>\w+):\s+(?P<value>\w+)$`)
    195 
    196 	// Template to convert "key: value" to "key=value" by
    197 	// referencing the values captured by the regex pattern.
    198 	template := []byte("$key=$value\n")
    199 
    200 	result := []byte{}
    201 
    202 	// For each match of the regex in the content.
    203 	for _, submatches := range pattern.FindAllSubmatchIndex(content, -1) {
    204 		// Apply the captured submatches to the template and append the output
    205 		// to the result.
    206 		result = pattern.Expand(result, template, content, submatches)
    207 	}
    208 	fmt.Println(string(result))
    209 	// Output:
    210 	// option1=value1
    211 	// option2=value2
    212 	// option3=value3
    213 }
    214 
    215 func ExampleRegexp_ExpandString() {
    216 	content := `
    217 	# comment line
    218 	option1: value1
    219 	option2: value2
    220 
    221 	# another comment line
    222 	option3: value3
    223 `
    224 
    225 	// Regex pattern captures "key: value" pair from the content.
    226 	pattern := regexp.MustCompile(`(?m)(?P<key>\w+):\s+(?P<value>\w+)$`)
    227 
    228 	// Template to convert "key: value" to "key=value" by
    229 	// referencing the values captured by the regex pattern.
    230 	template := "$key=$value\n"
    231 
    232 	result := []byte{}
    233 
    234 	// For each match of the regex in the content.
    235 	for _, submatches := range pattern.FindAllStringSubmatchIndex(content, -1) {
    236 		// Apply the captured submatches to the template and append the output
    237 		// to the result.
    238 		result = pattern.ExpandString(result, template, content, submatches)
    239 	}
    240 	fmt.Println(string(result))
    241 	// Output:
    242 	// option1=value1
    243 	// option2=value2
    244 	// option3=value3
    245 }
    246