-1

is it possible to have regex in Python that satisfies all the below STRING conditions?

1,000
1,000.00
$1,000.00
1000
-1000

I have the below but it doesn't satisfy all conditions:

if bool(re.compile(r"^\+?\-?\d*[.,]?\d*\%?$").match(text.strip())) == True:
   print ("Matched")
2
  • Did you try r"^\+?\-?\d*[.,]?\d*\%?\$" Commented Aug 17, 2021 at 16:47
  • It doesn't satisfy 1,700.00 Commented Aug 17, 2021 at 16:49

1 Answer 1

0

Try the pattern (?:[$-])?\d+(?:,\d+)*(?:\.\d+)?:

>>> import re
>>> text='''1,000
1,000.00
$1,000.00
1000
-1000'''

>>> re.findall('(?:[$-])?\d+(?:,\d+)*(?:\.\d+)?', text)
['1,000', '1,000.00', '$1,000.00', '1000', '-1000']

Understanding the pattern:

(?:[$-])?     Matches zero/one $ or - at the beginning
\d+           Matches one or more digits
(?:,\d+)*     Matches zero or more occurrence of comma separated numbers
(?:\.\d+)?    Matches zero or one occurrence of number after decimal at last

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.