How to extract if any digit present from list of matched word in text

Viewed 56
final_str = 'hello your total sale Fare Rs 741 your bill pls'
r = re.compile(r'\bSale\b|\bFare\b|\fare\b|\bRs\b', flags=re.I | re.X)
p=r.findall(final_str)
lis_con = p
matched = ''.join(lis_con)
res = final_str 
list_of_words = res.split()
gotdata = list_of_words[list_of_words.index(lis_con[0]) + 1]
print(gotdata)

So far I have tried this but not reaching the result, output expectation is it should check all list of words present in the dictionary and its return digit, for example, it matches Sale, Fare, Rs So its return the next word but I want to return the only digit in my case it should return 45. I think I need to check isDigit() any help highly appreciated.

1 Answers

You can use

\b(?:Sale|Fare|Rs)\s+(\d+(?:,\d+)*(?:\.\d+)?)

See the regex demo. Details:

  • \b - a word boundary
  • (?:Sale|Fare|Rs) - Sale, Fare or Rs strings
  • \s+ - one or more whitespaces
  • (\d+(?:,\d+)*(?:\.\d+)?) - Group 1: one or more digits, then zero or more repetitions of a comma and one or more digits, and then an optional occurrence of a dot and one or more digits.

See the Python demo:

import re
final_str = 'hello your total sale Fare Rs 741 your bill pls and Sale 2,804.00'
r = re.compile(r'\b(?:Sale|Fare|Rs)\s+(\d+(?:,\d+)*(?:\.\d+)?)', flags=re.I)
gotdata = r.findall(final_str)
print(gotdata)
# => ['741', '2,804.00']
Related