Home > database >  Regex pattern reads correctly but doesn't produce desired result
Regex pattern reads correctly but doesn't produce desired result

Time:08-13

I am testing the following regex:
(?<=\d{3}). (?!',') This at regex101 regex

Test string:

187 SURNAME First Names                     7 Every Street, Welltown Racing Driver

The sequence I require is:

  1. Begin after 3 digit numeral
  2. Read all characters
  3. Don't read the comma

In other words:

 SURNAME First Names                     7 Every Street

But as demo shows the negative lookahead to the comma has no bearing on the result. I can't see anything wrong with my lookarounds.

CodePudding user response:

. consumes everything.

So (?!,) is guaranteed to be true.

I'm not sure if using quotes is correct for whichever flavour of regex you are using. Bare comma seems more correct.

Try:

(?<=\d{3})[^,] 

CodePudding user response:

You could match the 3 digits, and make use of a capture group capturing any character except a comma.

\b\d{3}\b\s*([^,] )

Explanation

  • \b\d{3}\b Match 3 digits between word boundaries to prevent partial word matches
  • \s* Match optional whitespace chars
  • ([^,] ) Capture group 1, match 1 chars other than a comma

Regex demo

  • Related