diff options
author | Alex Myasoedov <msoedov@gmail.com> | 2017-11-18 12:49:54 -0500 |
---|---|---|
committer | Ian Lance Taylor <iant@golang.org> | 2018-06-30 01:04:30 +0000 |
commit | 0dc814cd7f6a5c01213169be17e823b69e949ada (patch) | |
tree | bad448c6d1790c2601265c456bb10ea2198bd86c /src/regexp | |
parent | da769814b83c4eb65681dbe682d07d4b902b554a (diff) | |
download | go-0dc814cd7f6a5c01213169be17e823b69e949ada.tar.gz go-0dc814cd7f6a5c01213169be17e823b69e949ada.zip |
regexp: examples for Regexp.FindIndex and Regexp.FindAllSubmatchIndex methods
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>
Diffstat (limited to 'src/regexp')
-rw-r--r-- | src/regexp/example_test.go | 42 |
1 files changed, 42 insertions, 0 deletions
diff --git a/src/regexp/example_test.go b/src/regexp/example_test.go index eb8cd4ea94..d65464665f 100644 --- a/src/regexp/example_test.go +++ b/src/regexp/example_test.go @@ -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 +} |