问题
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