如何将正则表达式从前瞻转换为中文?

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

How to convert regexp from lookahead

问题

我在PHP和其他代码中有以下的正则表达式,它的工作效果很好。

/^(?:(?=[^ ]+\d)(?:[A-Z0-9]+))|(?:[A-Z0-9]+) +?(?=.*\d)(?:[A-Z0-9]+)?

如何将正则表达式从前瞻转换为中文?

Debuggex演示

结果发现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]+)?

如何将正则表达式从前瞻转换为中文?

Debuggex Demo

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.

huangapple
  • 本文由 发表于 2017年2月13日 20:20:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/42203920.html
匿名

发表评论

匿名网友

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

确定