-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")
user13074756
  • 153
  • 3
  • 15

1 Answers1

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
ThePyGuy
  • 13,387
  • 4
  • 15
  • 42