JavaScript正则表达式的前瞻(Lookahead)

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

Javascript Regex Lookahead

问题

我不明白为什么这个正则表达式模式不能如预期般匹配。我在https://regexr.com上测试这个模式。

正则表达式 = /^1?((?=\d{3}))[-. ]?(\d{3})$/
样本 = 1(123) 123

我的理解是,第一个模式应该是数字1或什么都没有,然后是封闭括号内的3位数字,或者根本没有括号。在只使用(?\d{3})?之后,不应该有开括号,然后是可选的[-. ],接着是3位数字的结束。

英文:

I am not understanding why this regex pattern is not matching as expected. I am testing this pattern on https://regexr.com.

regex =/^1?\((?=\d{3}\))[-. ]?(\d{3})$/
sample = 1(123) 123

My understanding is first pattern should be number 1 or nothing then 3 digits in closed parentheses or no parentheses at all. There should not be open parentheses which will be the case when we only use (?(\d{3})\)? and after [-. ] which is optional, followed by 3 digits end.

答案1

得分: 1

"?="破坏了你的正则表达式,因为你想要匹配那3个数字。
如果你想要使括号变成可选的,但不想要任何开放的括号,你应该创建两种情况。

检查一下这个,如果你解决了你的问题:

regex=/^1?(((\d{3}))||(\d{3}))[-. ]?(\d{3})$/

英文:

"?=" is ruining your regex since you want to catch those 3 digits.
If you want to make paranthesis optinoal but you dont want any open one, you should create to cases then.

check that one if u solve your issue:

regex=/^1?(\((\d{3}\))||(\d{3}))[-. ]?(\d{3})$/

答案2

得分: 0

Lookahead 不消耗符号。因此,像这样的正则表达式 \((?=\d{3}\))[-. ] 需要在一方面 ( 后面跟着三个数字和 ),另一方面后面跟着破折号、点号或空格之一。

在你的情况下,你根本不需要 lookahead,简单的 ^1?\(\d{3}\)[-. ]?(\d{3})$ 就可以工作。

演示请看这里

英文:

Lookahead doesn't consume symbols. As a result, regex like this \((?=\d{3}\))[-. ] require, that on one hand, ( is followed by three digits and ), but on the other hand followed by either of dash, dot or space.

In your case, you don't need lookaheads at all, simple ^1?\(\d{3}\)[-. ]?(\d{3})$ should work.

Demo here.

答案3

得分: 0

我不确定我是否正确理解了您的要求,但我认为您希望以下情况能够正常工作?

1(234) 567
1(234)567
(234) 567
(234)567
1234 567
1234567
234 567
234567

而且,可能更棘手的是,您希望这三个匹配组分别是第一个数字(如果有的话),可选括号内的三个数字,以及最后的三个数字。

这是我的第一次尝试,使用前瞻来检查是否有括号的有效情况,然后获取两组数字的两个组。

^(1?)(?=\d{3}[-. \d]+|(\d{3}))(?(\d{3}))?[-. ]?(\d{3})$

英文:

I am not 100% sure I read your requirements correctly, but I think you want these scenarios to work?

1(234) 567
1(234)567
(234) 567
(234)567
1234 567
1234567
234 567
234567

And, probably more trickily, you want the 3 matching groups to be the first digit if any, the 3 numbers inside the optional parenthesis, and then the final 3 numbers.

This is my first attempt, using a look-ahead to check for the valid cases of with/without parenthesis, then following that with grabbing the two groups for the two sets of numbers.

^(1?)(?=\d{3}[-. \d]+|\(\d{3}\))\(?(\d{3})\)?[-. ]?(\d{3})$

huangapple
  • 本文由 发表于 2023年6月29日 21:04:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/76581340.html
匿名

发表评论

匿名网友

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

确定