Walucas
Walucas

Reputation: 2568

Regex not ignoring match

I have the following regex: ^(?P<X1>.*?(?!\.00))(?:\s(?P<X2>[0-9\.]*))$

And it should not match this:

Lore Ipsum. Lore 3.00 3.00

Lore Ipsum. Lore 3.00 Lore Ipsum 3.00

It still needs to capture this:

Lore Ipsum. Lore 3.00

Lore Ipsum. Lore 1 3.00

I am doing the negative lookahead, but for some reason the first 3.00 is still being captured, any help is appreciated.

Upvotes: 0

Views: 35

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626689

You can use

^(?!.*\.00.*\s\S+$)\s?(?P<X1>.*?)(?:\s(?P<X2>\d+(?:\.\d+)?))?$

See regex demo #1.

The point here is to use a lookahead at the start of string and fail the match if there is .00 before the final word.

Details

  • ^ - start of string
  • (?!.*\.00.*\s\S+$) - a negative lookahead that fails the match if there is any text, .00, any text, whitespace, one or more non-whitespace chars and end of string immediately to the right of the current location
  • \s? - an optional whitespace
  • (?P<X1>.*?) - Group "X1": any zero or more chars other than line break chars, as few as possible
  • \s - a whitespace
  • (?:\s(?P<X2>\d+(?:\.\d+)?))? - an optional sequence of a whitespace and then an "X2" group capturing one or more digits and then an optional sequence of a . and one or more digits
  • $ - end of string.

Upvotes: 1

Related Questions