Go 正则表达式中的负前瞻 [英] Negative look-ahead in Go regular expressions

查看:35
本文介绍了Go 正则表达式中的负前瞻的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 Go 中使用否定前瞻.

I'm trying to use negative look-aheads in Go.

以下正则表达式:BBB(((?!BBB).)*)EEE

http://rubular.com/r/Zw1vopp1MF

然而,在围棋中我得到:

However, in Go I get:

error parsing regexp: invalid or unsupported Perl syntax: `(?!`

有其他选择吗?

推荐答案

由于技术原因,不支持负前瞻,特别是因为它与库的 O(n) 时间保证相冲突.请参阅 golang-nuts 小组讨论,以及<中的警告部分a href="http://swtch.com/~rsc/regexp/regexp3.html">野外正则表达式匹配.

Negative lookahead isn't supported for technical reasons, specifically because it conflicts with the O(n)-time guarantees of the library. See the golang-nuts group discussion about this, as well as the Caveats section in Regular Expression Matching in the Wild.

您可以表达您所描述的正则表达式,而无需否定前瞻:

You can express the regular expression you've described without negative lookahead:

BBB([^B]|B[^B]|BB[^B])*EEE

这是一个示例来演示:

package main

import (
    "fmt"
    "regexp"
)

func main() {
    re := regexp.MustCompile(`BBB([^B]|B[^B]|BB[^B])*EEE`)
    fmt.Printf("%#v
", re.FindAllString("BBB EEE BBB..BBB...EEE", -1))
}

这篇关于Go 正则表达式中的负前瞻的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆