Why is this regular expression failing to match the second 6 digit number?

喜欢而已 提交于 2021-02-07 23:46:41

问题


I can't understand why the following PowerShell is not working:

([regex]"(^|\D)(\d{6})(\D|$)").Matches( "123456 123457" ).Value

The code above code produces:

123456

Why is it not matching both numbers?


回答1:


The "(^|\D)(\d{6})(\D|$)" regex matches and consumes a non-digit char before and after 6 digits (that is, the space after 123456 is consumed during the first iteration).

Use a non-consuming construct, lookbehind and lookahead:

"(?<!\d)\d{6}(?!\d)"

See a .NET regex demo.

The (?<!\d) negative lookbehind fails the match if there is a digit immediately to the left of the current location and (?!\d) negative lookahead fails the match if there is a digit immediately after the current position, without actually moving the regex index inside the string.



来源:https://stackoverflow.com/questions/43606611/why-is-this-regular-expression-failing-to-match-the-second-6-digit-number

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!