英文:
Go Regex to match tags with bracket
问题
我想使用正则表达式包来获取括号内所有标签的索引。
str := "[tag=blue]Hello [tag2=red,tag3=blue]Good"
rg := regexp.MustCompile(`(?:^|\W)\[([\w-]+)=([\w-]+)\]`)
rgi := fmtRegex.FindAllStringIndex(str, -1)
fmt.Println(rgi)
// 想要的索引为:
// [tag=blue], [tag2=red,tag3=blue]
这个正则表达式需要返回 [tag=blue], [tag2=red,tag3=blue]
的索引。
但是它只返回 [tag=blue]
。
如何修复这个正则表达式 (?:^|\W)\[([\w-]+)=([\w-]+)\]
,以便在括号中有多个标签时也能匹配逗号?
英文:
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
答案1
得分: 1
我想评论@Avinash Raj的答案,但我没有足够的声望...所以:
> 看起来你想要这样的东西,
>
> ...
>
> \B\[([\w-]+)=([\w-]+)(?:,[\w-]+=[\w-]+)*\]
提供的正则表达式只会匹配字符串中的第一个和最后一个key=value对。如果有这样的字符串:
[tag=val,tag1=val1,tag2=val2,tag3=val3]
该正则表达式只会匹配tag
、val
、tag3
和val3
。
如果你想匹配所有的键值对,我建议使用纯Go而不是正则表达式。这在Go中应该是相当简单的。
如果你只需要匹配的索引,你可以使用上述的正则表达式,然后以其他方式解析标签。
英文:
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.
答案2
得分: 0
似乎你想要这样的东西,
(?<!\w)\[([\w-]+)=([\w-]+)(?:,[\w-]+=[\w-]+)*\]
或者
\B\[([\w-]+)=([\w-]+)(?:,[\w-]+=[\w-]+)*\]
\B
匹配两个单词字符或两个非单词字符之间的位置。
英文:
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.
答案3
得分: 0
golang Regexp包中接受的正确正则表达式,用于选择多个括号中的标签表达式是:
rg := regexp.MustCompile(\[([\w-]+)=([\w-]+)(?:,([\w-]+)=([\w-]+))*\]
)
看看这是否是你要找的...
更新:刚刚意识到这个问题已经被@ndyakov回答过了。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论