英文:
How to convert regexp from lookahead
问题
我在PHP和其他代码中有以下的正则表达式,它的工作效果很好。
/^(?:(?=[^ ]+\d)(?:[A-Z0-9]+))|(?:[A-Z0-9]+) +?(?=.*\d)(?:[A-Z0-9]+)?
结果发现Go语言不支持lookahead,我不知道如何转换这个正则表达式。
Debuggex链接中有一些我之前用来测试代码的数据。
英文:
I have the following Regex in PHP and other code that is doing a great job.
/^(?:(?=[^ ]+\d)(?:[A-Z0-9]+))|(?:[A-Z0-9]+) +?(?=.*\d)(?:[A-Z0-9]+)?
It turns out that Go doesn't support lookheads and I'm at a loss on how to convert it across.
The Debuggex link has some test data I was using to qualify the code before.
答案1
得分: 1
首先,替代项/^...
的左侧不匹配任何内容,因为/
永远不会出现在输入的开头之前。
剩下的只有(?:[A-Z0-9]+) +?(?=.*\d)
,可以表示为:
((?:[A-Z0-9]+) ).*\d.*
使用的" +?"
与" "
的效果完全相同。
但请注意,这比原始表达式消耗更多的输入,这是不可避免的。您原始匹配现在在第1组中。
英文:
Firstly, the left hand side of the alternation /^...
matches nothing, because /
can never appear before start of input.
That leaves just (?:[A-Z0-9]+) +?(?=.*\d)
, which can be expressed as:
((?:[A-Z0-9]+) ).*\d.*
The term " +?"
as used is identical in effect to just " "
.
Note however that this consumes more input than the original, which is unavoidable. Your original match is now in group 1.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论