负向回顾失败

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

Negative Lookbehind failure

问题

我在我的Golang代码中有一个小的MySQL表检查脚本。我想做的最后一件事是在应用程序启动时存储任何可能的enum值,这样我就可以从缓冲区中读取它,而不必为API调用不断描述表。

现在,enum的内容可能是'value1','value2','value\'s3'这样的,简单的正则表达式如'(.*?)'无法工作,因为在value\'s3中有一个转义的引号。所以我写了一个负向回顾,只有在非转义引号的情况下才匹配。虽然不完美,但至少有一些额外的检查,而且我自己管理数据库结构,所以我可以在上面做个小笔记。

到了关键点;负向回顾失败了'(.*?)(?<!\\)'

panic: regexp: Compile(`'(.*?)(?<!\\)'`): error parsing regexp: invalid or unsupported Perl syntax: `(?<`

代码:

var enumMatchValues = regexp.MustCompile(`'(.*?)(?<!\\)'`)
values := enumMatchValues.FindAllStringSubmatch(theRawEnumValuesString, -1)

正向回顾/负向回顾是否正式不是正则表达式功能的核心部分,还是这只是Golang尚未实现的功能?

是否有其他解决方法或扩展的Go正则表达式包来解决这个问题?

英文:

I have a little MySQL table inspector script in my Golang code. The last thing I wanted to do was to store any possible enum value when my application starts so I can read it out of the buffer instead of having to describe the tables constantly for API calls.

Now with enum's stuff like &#39;value1&#39;,&#39;value2&#39;,&#39;value\&#39;s3 can occur, where simple RegEx like &#39;(.*?)&#39; doesn't work because of the escaped quotation-mark in value\&#39;s3. So I wrote a negative look-behind to make it match only if it is a non-escaped quotation-mark. Not totally flawless but at least some extra checks and I manage the database structure by myself so it's something I can just keep a small note on.

To the point; the negative-lookbehind fails &#39;(.*?)(?&lt;!\\)&#39;:

panic: regexp: Compile(`&#39;(.*?)(?&lt;!\\)&#39;`): error parsing regexp: invalid or unsupported Perl syntax: `(?&lt;`

Code:

var enumMatchValues = regexp.MustCompile(`&#39;(.*?)(?&lt;!\\)&#39;`)
values := enumMatchValues.FindAllStringSubmatch(theRawEnumValuesString, -1)

Are the lookaheads/lookbehinds officially not part of the core of the RegEx functionality or is this just something Golang hasn't implemented yet?

Would there be another workaround or extended RegEx package for Go to solve this?

答案1

得分: 2

看起来你想要翻译一段代码。以下是翻译的结果:

回顾不受支持,你可以使用一个可能的解决方法:

    re := regexp.MustCompile(`&#39;(.*?[^\\]|)&#39;`)
    values := re.FindAllStringSubmatch(theRawEnumValuesString, -1)

希望对你有帮助!如果你有其他问题,请随时提问。

英文:

Lookarounds are not supported, you could use a possible workaround:

re := regexp.MustCompile(`&#39;(.*?[^\\]|)&#39;`)
values := re.FindAllStringSubmatch(theRawEnumValuesString, -1)

huangapple
  • 本文由 发表于 2015年3月1日 02:52:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/28785505.html
匿名

发表评论

匿名网友

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

确定