Reputation:
I want to get the index of all tags inside brackets using regex package.
str := "[tag=blue]Hello [tag2=red,tag3=blue]Good"
rg := regexp.MustCompile(`(?:^|\W)\[([\w-]+)=([\w-]+)\]`)
rgi := fmtRegex.FindAllStringIndex(str, -1)
fmt.Println(rgi)
// Want index for:
// [tag=blue], [tag2=red,tag3=blue]
The regex needs to return indexes for [tag=blue], [tag2=red,tag3=blue]
but it only returns [tag=blue]
.
How do I fix this regex (?:^|\W)\[([\w-]+)=([\w-]+)\]
so that I can also match the comman when there is more than one tags in the brackets
Upvotes: 0
Views: 1486
Reputation: 435
The correct regexp accepted by golang Regexp package to select tag expressions in the multiple brackets is:
rg := regexp.MustCompile(`\[([\w-]+)=([\w-]+)(?:,([\w-]+)=([\w-]+))*\]`)
See, if that was what you were looking for...
UPDATE: Just realized that it was already answered by @ndyakov.
Upvotes: 0
Reputation: 37
I would like to post a comment to the Answer by @Avinash Raj but I don't have enought Repotation... so:
Seems like you want something like this,
...
\B\[([\w-]+)=([\w-]+)(?:,[\w-]+=[\w-]+)*\]
The provided regular expression will match only the first and the last pair of key=value in the string. Having something like:
[tag=val,tag1=val1,tag2=val2,tag3=val3]
The regular expression will only match the tag
, val
, tag3
and val3
.
If you want to match all of them I would suggest using pure go without regular expressions. This is something that should be almost straight forward in go.
If you actually need only the index for the match, you can use the above regular expression and then parse the tags some other way.
Upvotes: 1
Reputation: 174796
Seems like you want something like this,
(?<!\w)\[([\w-]+)=([\w-]+)(?:,[\w-]+=[\w-]+)*\]
OR
\B\[([\w-]+)=([\w-]+)(?:,[\w-]+=[\w-]+)*\]
\B
matches between two word characters or two non-word characters.
Upvotes: 0