Home > Software engineering >  Regex: Filter percentage with negative lookahead
Regex: Filter percentage with negative lookahead

Time:12-28

Must be silly but I can't figure out how to ignore/skip percentages in a string, and only capture amounts (any locale).

e.g. 6.000 6.000% 12.24 with regex [.,\d] \d(?! ?%) still matches the middle rate with 6.00.

See https://regex101.com/r/jn7gHD/2

Desired outcome: match 6.000 and 12.24, not 6.000% (or 6.000 % if encountered)

CodePudding user response:

It matches the 6.00 in 6.000% because it's followed by 0, which isn't %.

You can solve this by forcing the match to end at a word boundary.

[.,\d] \d\b(?! ?%)

CodePudding user response:

Alternative regex: Don't match a amount if there's a \s*% at the end:

(?!\d (?:[.,]\d )*\s*%)\d (?:[.,]\d )*

Regex demo.

  • Related