Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 950
Bruno Avatar asked Dec 29 '25 05:12

Bruno


1 Answers

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.

like image 117
Wiktor Stribiżew Avatar answered Dec 30 '25 22:12

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!