Alex roy
Alex roy

Reputation: 27

How to extract multiple numbers after string

text = " There are submitted charges 1500.00 900.00 1300.00 and amount paid by the XXXX patient resp 50 90 1300 9000"

ref_no1 = re.findall(r"(?:(?<=submitted charges))[\d-]+",text)
ref_no2 = re.findall(r"(?:(?<=patient resp))[\d-]+",text)
print(ref_no1)
print(ref_no2)


Required solution:
ref_no1: ['1500.00','900.00','1300.00']
ref_no2: ['50','90','1300','9000']

Is there any solution to get all numbers after a string

Upvotes: 1

Views: 102

Answers (1)

Dan Constantinescu
Dan Constantinescu

Reputation: 1541

I would use partition() and then extract the numbers after the keyword. Something like this:

def extract_numbers(text: str, keyword: str):

    _, _, after_keyword = text.partition(keyword)
    result = []

    for item in after_keyword.split():
        try:
            is_number = float(item)
            result.append(item)
        except ValueError:
            break

    return result

print(extract_numbers(text, "charges"))
print(extract_numbers(text, "resp"))

Given your text as an input, above will return:

['1500.00', '900.00', '1300.00']
['50', '90', '1300', '9000']

Upvotes: 1

Related Questions