I am trying to parse the following string:
`%%% First %%% part 1 %%% Second %%% part2`
This goes on and on into an unknown number of parts...e.g. Third, Fourth, Another, Car, Airplane, etc... all are separated by "%%% Something %%%"
I have:
package main
import (
"fmt"
"regexp"
)
func main() {
reg:= regexp.MustCompile(`(?P<part>%%% .* %%%)+`)
match := reg.FindStringSubmatch(`%%% First %%% part 1 %%% Second %%% part2`)
if len(match) == 0 {
fmt.Println("not found")
}
for i, g := range reg.SubexpNames() {
if i == 0 || g == "" {
continue
}
switch g {
case "part":
fmt.Println("part:", match[i])
default:
fmt.Printf("what group %q", g)
}
}
}
Gives:
part: %%% First %%% part 1 %%% Second %%%
How do I get output so that it prints like the following where part 1 and part 2 are separate matching groups? I would like to ignore "First" entirely and just focus on "Second":
part 2
This makes the assumption that the pieces you are trying to capture follow the format of %%% Descriptor String %%% part
where it will only print the part segment. This is expecting this pattern to repeat.
Also I added in the closing %%% that was missing from the given string.
With this pattern, it doesn't matter on having the closing %%%, but they don't harm either.
package main
import (
"fmt"
"regexp"
)
func main() {
reg := regexp.MustCompile(`%%%[^%]*%%%(?P<part>[^%]*)`)
match := reg.FindAllStringSubmatch(`%%% First %%% part 1 %%% Second %%% part2 %%% Third %%% wobble wobble %%%`, -1)
if len(match) == 0 {
fmt.Println("not found")
}
for i, _ := range match {
fmt.Println("part:", match[i][1])
}
}
This will print out:
part: part 1 part: part2 part: wobble wobble
Don't use regexp, use split
package main
import (
"fmt"
"strings"
)
func main() {
example := `%%% First %%% part 1 %%% Second %%% part2`
other := strings.Split(example, "%%%")
fmt.Println(other)
}