Why doesn't this regex match the second 6 digit number?

I can't figure out why the following PowerShell isn't working:

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

      

The code above is the code:

123456

      

Why doesn't this match both numbers?

+3


source to share


1 answer


The regex "(^|\D)(\d{6})(\D|$)"

matches and consumes a non-char before and after 6 digits (i.e. the space after is 123456

consumed during the first iteration).

Use indecent construction, lookbehind and lookahead:

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

      



See .NET regex demo .

A negative lookbehind (?<!\d)

does not match if the near is to the left of the current location, and a (?!\d)

negative lookahead does not match if there is a digit immediately after the current position, without actually moving the regex index within the string.

+6


source







All Articles