From 0dc814cd7f6a5c01213169be17e823b69e949ada Mon Sep 17 00:00:00 2001 From: Alex Myasoedov Date: Sat, 18 Nov 2017 12:49:54 -0500 Subject: [PATCH] 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 --- src/regexp/example_test.go | 42 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 42 insertions(+) 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\w+):\s+(?P\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\w+):\s+(?P\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 +} -- 2.50.0