How can I split input strings below by regex in Go? Examples of strings:
I know how to split by dot, but how can I avoid splitting in quotes?
"a.b.c.d" -> ["a", "b", "c", "d"]
"a."b.c".d" -> ["a", "b.c", "d"]
"a.'b.c'.d" -> ["a", "b.c", "d"]
How can I split input strings below by regex in Go? Examples of strings:
I know how to split by dot, but how can I avoid splitting in quotes?
"a.b.c.d" -> ["a", "b", "c", "d"]
"a."b.c".d" -> ["a", "b.c", "d"]
"a.'b.c'.d" -> ["a", "b.c", "d"]
Here is another option with a somewhat less hacky regex. It uses the trash bin trick. So the real data is on the (first and second) capturing groups.
It works even with nested quotes like this: "a.'b.c'.d.e."f.g.h""
as long as there is not a recursion of 2 or more levels (as in here: "a.'b."c.d"'"
, quotes inside quotes inside quotes).
The regex is this: ^"|['"](\w+(?:\.\w+)*)['"]|(\w+)
And the code:
package main
import (
"regexp"
"fmt"
)
func main() {
var re = regexp.MustCompile(`^"|['"](\w+(?:\.\w+)*)['"]|(\w+)`)
var str = `"a.'b.c'.d.e."f.g.h""`
result := re.FindAllStringSubmatch(str, -1)
for _, m := range result {
if (m[1] != "" || m[2] != "") {
fmt.Print(m[1] + m[2] + "
")
}
}
}
Input:
"a.'b.c'.d.e."f.g.h""
Output:
a
b.c
d
e
f.g.h