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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With