0

I have a string in Python with the value 'I take $80 from you and give you $ 100.00 back.'. Notice the difference between the two monetary values here. There is no white space between the '$' symbol and value in '$80' but there is a space between '$' and value in '$ 100'.

And I want to return a list which looks like ['$80', '$100.00'] or ['$80', '$ 100.00']. How can I achieve this using Python? I have tried this code which returns the list ['$80', '$100']:

>>> text = 'I take $80 from you and give you $ 100 back.'
>>> import re
>>> re.findall('\$\s*\d+', text)
['$80', '$ 100']
Aafaz
  • 51
  • 4

1 Answers1

0

You can use (?:\.\d+)? in addition to above regex pattern to match one or zero occurrence at last for the values from decimal point.

>>> re.findall('\$\s*\d+(?:\.\d+)?', text)
['$80', '$ 100']
ThePyGuy
  • 17,779
  • 5
  • 18
  • 45
  • Thanks @ThePyGuy for your response. I have one more doubt in this thread when the number is in the thousands. If I try the following code with a thousand number having commas in between, it looks like: – ``` >> text = 'I take $80 from you and give you $ 1,000.00 back.' >>> import re >>> re.findall('\$\s*\d+(?:\.\d+)?', text) ['$80', '$ 1'] ``` Is there any way I can get rid of the commas using regex or get the entire amount i.e. $ 1000? – Aafaz Aug 16 '21 at 21:17
  • 1
    **regex** solution always depends on what the data looks like, previously, your data had only integer numbers i.e. `I take $80 from you and give you $ 100 back.`, so proposed solution had regex `'\$\s*\d+`, then you said there can be floating point numbers as well, so the regex changed to `\$\s*\d+(?:\.\d+)?`, now you are saying it can have comma as well, that means the regex needs to be modified to capture comma separated numbers as well. – ThePyGuy Aug 16 '21 at 21:21
  • 1
    You can try something similar to: `re.findall('\$\s*\d+(?:,\d+)*(?:\.\d+)?', text)` for the text `'I take $80 from you and give you $ 1,000.00 back.' ` – ThePyGuy Aug 16 '21 at 21:29
  • Also, Looking at your profile, you haven't accepted answers in any of the question you have asked. Please click on `✓` icon appearing on an answer that works for you, to accept that answer as the solution to your question so that it no longer appears in unanswered queue. – ThePyGuy Aug 16 '21 at 21:36