Debian Codegraph @

src/regexp/example_test.go

raw
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
232 re2 := regexp.MustCompile(`a(?P<1W>x*)b`)
233 fmt.Printf("%s\n", re2.ReplaceAll([]byte("-ab-axxb-"), []byte("$1W")))
234 fmt.Printf("%s\n", re2.ReplaceAll([]byte("-ab-axxb-"), []byte("${1}W")))
235
236 // Output:
237 // -T-T-
238 // --xx-
239 // ---
240 // -W-xxW-
241 // --xx-
242 // -W-xxW-
243 }
244
245 func ExampleRegexp_ReplaceAllLiteralString() {
246 re := regexp.MustCompile(`a(x*)b`)
247 fmt.Println(re.ReplaceAllLiteralString("-ab-axxb-", "T"))
248 fmt.Println(re.ReplaceAllLiteralString("-ab-axxb-", "$1"))
249 fmt.Println(re.ReplaceAllLiteralString("-ab-axxb-", "${1}"))
250 // Output:
251 // -T-T-
252 // -$1-$1-
253 // -${1}-${1}-
254 }
255
256 func ExampleRegexp_ReplaceAllString() {
257 re := regexp.MustCompile(`a(x*)b`)
258 fmt.Println(re.ReplaceAllString("-ab-axxb-", "T"))
259 fmt.Println(re.ReplaceAllString("-ab-axxb-", "$1"))
260 fmt.Println(re.ReplaceAllString("-ab-axxb-", "$1W"))
261 fmt.Println(re.ReplaceAllString("-ab-axxb-", "${1}W"))
262
263 re2 := regexp.MustCompile(`a(?P<1W>x*)b`)
264 fmt.Printf("%s\n", re2.ReplaceAllString("-ab-axxb-", "$1W"))
265 fmt.Println(re.ReplaceAllString("-ab-axxb-", "${1}W"))
266
267 // Output:
268 // -T-T-
269 // --xx-
270 // ---
271 // -W-xxW-
272 // --xx-
273 // -W-xxW-
274 }
275
276 func ExampleRegexp_ReplaceAllStringFunc() {
277 re := regexp.MustCompile(`[^aeiou]`)
278 fmt.Println(re.ReplaceAllStringFunc("seafood fool", strings.ToUpper))
279 // Output:
280 // SeaFooD FooL
281 }
282
283 func ExampleRegexp_SubexpNames() {
284 re := regexp.MustCompile(`(?P<first>[a-zA-Z]+) (?P<last>[a-zA-Z]+)`)
285 fmt.Println(re.MatchString("Alan Turing"))
286 fmt.Printf("%q\n", re.SubexpNames())
287 reversed := fmt.Sprintf("${%s} ${%s}", re.SubexpNames()[2], re.SubexpNames()[1])
288 fmt.Println(reversed)
289 fmt.Println(re.ReplaceAllString("Alan Turing", reversed))
290 // Output:
291 // true
292 // ["" "first" "last"]
293 // ${last} ${first}
294 // Turing Alan
295 }
296
297 func ExampleRegexp_SubexpIndex() {
298 re := regexp.MustCompile(`(?P<first>[a-zA-Z]+) (?P<last>[a-zA-Z]+)`)
299 fmt.Println(re.MatchString("Alan Turing"))
300 matches := re.FindStringSubmatch("Alan Turing")
301 lastIndex := re.SubexpIndex("last")
302 fmt.Printf("last => %d\n", lastIndex)
303 fmt.Println(matches[lastIndex])
304 // Output:
305 // true
306 // last => 2
307 // Turing
308 }
309
310 func ExampleRegexp_Split() {
311 a := regexp.MustCompile(`a`)
312 fmt.Println(a.Split("banana", -1))
313 fmt.Println(a.Split("banana", 0))
314 fmt.Println(a.Split("banana", 1))
315 fmt.Println(a.Split("banana", 2))
316 zp := regexp.MustCompile(`z+`)
317 fmt.Println(zp.Split("pizza", -1))
318 fmt.Println(zp.Split("pizza", 0))
319 fmt.Println(zp.Split("pizza", 1))
320 fmt.Println(zp.Split("pizza", 2))
321 // Output:
322 // [b n n ]
323 // []
324 // [banana]
325 // [b nana]
326 // [pi a]
327 // []
328 // [pizza]
329 // [pi a]
330 }
331
332 func ExampleRegexp_Expand() {
333 content := []byte(`
334 # comment line
335 option1: value1
336 option2: value2
337
338 # another comment line
339 option3: value3
340 `)
341
342 // Regex pattern captures "key: value" pair from the content.
343 pattern := regexp.MustCompile(`(?m)(?P<key>\w+):\s+(?P<value>\w+)$`)
344
345 // Template to convert "key: value" to "key=value" by
346 // referencing the values captured by the regex pattern.
347 template := []byte("$key=$value\n")
348
349 result := []byte{}
350
351 // For each match of the regex in the content.
352 for _, submatches := range pattern.FindAllSubmatchIndex(content, -1) {
353 // Apply the captured submatches to the template and append the output
354 // to the result.
355 result = pattern.Expand(result, template, content, submatches)
356 }
357 fmt.Println(string(result))
358 // Output:
359 // option1=value1
360 // option2=value2
361 // option3=value3
362 }
363
364 func ExampleRegexp_ExpandString() {
365 content := `
366 # comment line
367 option1: value1
368 option2: value2
369
370 # another comment line
371 option3: value3
372 `
373
374 // Regex pattern captures "key: value" pair from the content.
375 pattern := regexp.MustCompile(`(?m)(?P<key>\w+):\s+(?P<value>\w+)$`)
376
377 // Template to convert "key: value" to "key=value" by
378 // referencing the values captured by the regex pattern.
379 template := "$key=$value\n"
380
381 result := []byte{}
382
383 // For each match of the regex in the content.
384 for _, submatches := range pattern.FindAllStringSubmatchIndex(content, -1) {
385 // Apply the captured submatches to the template and append the output
386 // to the result.
387 result = pattern.ExpandString(result, template, content, submatches)
388 }
389 fmt.Println(string(result))
390 // Output:
391 // option1=value1
392 // option2=value2
393 // option3=value3
394 }
395
396 func ExampleRegexp_FindIndex() {
397 content := []byte(`
398 # comment line
399 option1: value1
400 option2: value2
401 `)
402 // Regex pattern captures "key: value" pair from the content.
403 pattern := regexp.MustCompile(`(?m)(?P<key>\w+):\s+(?P<value>\w+)$`)
404
405 loc := pattern.FindIndex(content)
406 fmt.Println(loc)
407 fmt.Println(string(content[loc[0]:loc[1]]))
408 // Output:
409 // [18 33]
410 // option1: value1
411 }
412
413 func ExampleRegexp_FindAllSubmatchIndex() {
414 content := []byte(`
415 # comment line
416 option1: value1
417 option2: value2
418 `)
419 // Regex pattern captures "key: value" pair from the content.
420 pattern := regexp.MustCompile(`(?m)(?P<key>\w+):\s+(?P<value>\w+)$`)
421 allIndexes := pattern.FindAllSubmatchIndex(content, -1)
422 for _, loc := range allIndexes {
423 fmt.Println(loc)
424 fmt.Println(string(content[loc[0]:loc[1]]))
425 fmt.Println(string(content[loc[2]:loc[3]]))
426 fmt.Println(string(content[loc[4]:loc[5]]))
427 }
428 // Output:
429 // [18 33 18 25 27 33]
430 // option1: value1
431 // option1
432 // value1
433 // [35 50 35 42 44 50]
434 // option2: value2
435 // option2
436 // value2
437 }
438
439 func ExampleRegexp_FindAllIndex() {
440 content := []byte("London")
441 re := regexp.MustCompile(`o.`)
442 fmt.Println(re.FindAllIndex(content, 1))
443 fmt.Println(re.FindAllIndex(content, -1))
444 // Output:
445 // [[1 3]]
446 // [[1 3] [4 6]]
447 }