nobody
nobody

Reputation: 310

regex - Match pattern without prefix before pattern

I would like to match amounts without $. I've tried (?<!\$)\d+\.\d{2} so far. It's probably something simple but I'm missing it :(

strings

$100.00 50.00
1.99 $150.50 200.00

How would get the match to be below?

50.00
1.99 200.00

Upvotes: 2

Views: 335

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626816

Just FYI: you should provide more realistic examples because right now, you may just solve the issue by splitting with whitespace and returning all items that do not start with $:

[x for x in text.split() if not x.startswith('$')]

I would include a digit check into the negative lookahead and also add a digit check on the right (since the \d{2} only matches two digits, but does not prevent from matching when there are 3 or more).

r'(?<![$\d])\d+\.\d{2}(?!\d)'

See the regex demo.

Details

  • (?<![$\d]) - no $ or digit allowed immediately on the left
  • \d+ - one or more digits
  • \. - a dot
  • \d{2} - two digits
  • (?!\d) - no digit allowed on the right.

Python demo:

import re
text = "$100.00 50.00\n1.99 $150.50 200.00"
print( [x for x in text.split() if not x.startswith('$')] )
# => ['50.00', '1.99', '200.00']
print( re.findall(r'(?<![$\d])\d+\.\d{2}(?!\d)', text) )
# => ['50.00', '1.99', '200.00']

Upvotes: 2

Related Questions