user4211028
user4211028

Reputation:

Go Regex to match tags with bracket

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

Answers (3)

tez
tez

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-]+))*\]`)

Playground

See, if that was what you were looking for...

UPDATE: Just realized that it was already answered by @ndyakov.

Upvotes: 0

ndyakov
ndyakov

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

Avinash Raj
Avinash Raj

Reputation: 174796

Seems like you want something like this,

(?<!\w)\[([\w-]+)=([\w-]+)(?:,[\w-]+=[\w-]+)*\]

DEMO

OR

\B\[([\w-]+)=([\w-]+)(?:,[\w-]+=[\w-]+)*\]

\B matches between two word characters or two non-word characters.

DEMO

Upvotes: 0

Related Questions