Go正则表达式,负向前瞻的替代方案

huangapple go评论152阅读模式
英文:

Go regex, Negative Look Ahead alternative

问题

我正在尝试使用Go正则表达式实现(?<!\\{)\\[[a-zA-Z0-9_]+\\](?!\\})的匹配。

匹配的值将类似于[ua][ua_enc],而不匹配的值应该是{[ua]}{[ua_enc]}

由于Go不支持负向前瞻,你可以使用什么替代表达式呢?

英文:

I am trying to implement the regex (?<!\\{)\\[[a-zA-Z0-9_]+\\](?!\\}) with go regex.

Match value will be like [ua] and [ua_enc] and unmatched should be {[ua]} and {[ua_enc]}

As Negative lookahead is not supported in Go, what may be the alternative expression for this?

答案1

得分: 2

对于这个问题,没有其他的替代表达方式。使用简单的 (?:[^{]|^)(...)(?:[^}]|$) 来捕获所需的匹配,并断言前后字符不是大括号,这种方法可能会有一些问题:你需要使用第一个捕获组而不是完整的匹配结果,并且当两个匹配之间只有一个字符时(例如 [foo]_[bar]),它会失败。最好的方法是使用 FindAllStringSubmatchIndex 并手动检查前后字符,以确保它们不是正则表达式外的大括号。

英文:

There is no alternative expression for this. Using plain (?:[^{]|^)(...)(?:[^}]|$) to capture the intended match and assert the previous and next characters are not braces will kind-of work: you will need to work with the first capture group instead of with the full match, and it will fail when there is only a single character between two matches (e.g. [foo]_[bar]). The best way, really, is to use FindAllStringSubmatchIndex and manually check the previous and next characters to make sure they are not braces outside of regexp.

huangapple
  • 本文由 发表于 2017年1月25日 14:16:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/41844710.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定