]> Cypherpunks repositories - gostls13.git/commitdiff
regexp: examples for Regexp.FindIndex and Regexp.FindAllSubmatchIndex methods
authorAlex Myasoedov <msoedov@gmail.com>
Sat, 18 Nov 2017 17:49:54 +0000 (12:49 -0500)
committerIan Lance Taylor <iant@golang.org>
Sat, 30 Jun 2018 01:04:30 +0000 (01:04 +0000)
This commit adds examples that demonstrate usage in a practical way.

Change-Id: I105baf610764c14a2c247cfc0b0c06f27888d377
Reviewed-on: https://go-review.googlesource.com/78635
Reviewed-by: Ian Lance Taylor <iant@golang.org>
src/regexp/example_test.go

index eb8cd4ea94c3d123b801f6e7ebfb1d4d76db64b1..d65464665f77986ea2c946c6de6246e3a5a4badf 100644 (file)
@@ -249,3 +249,45 @@ func ExampleRegexp_ExpandString() {
        // option2=value2
        // option3=value3
 }
+
+func ExampleRegexp_FindIndex() {
+       content := []byte(`
+       # comment line
+       option1: value1
+       option2: 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 ExampleRegexp_FindAllSubmatchIndex() {
+       content := []byte(`
+       # comment line
+       option1: value1
+       option2: 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: value1
+       // option1
+       // value1
+       // [35 50 35 42 44 50]
+       // option2: value2
+       // option2
+       // value2
+}