英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论