PYTHON – Find a number preceded by specific string

Question:

I have a text, where I want to find numbers (could be any number), preceded by specific word. (for example "your debt is 100 dollars)

I want to find a way to find "is 100".

I have already found the way to find a number followed by specific word, but I couldn’t manage to do the toher way.

EX:(100 dollars)

import re
text="Your gift is 100 dollars"
print(re.findall(r'bd+s*dollars[s]?b', text))
['100 dollars']
Asked By: Agustin Tettamanti

||

Answers:

Using split and a comprehension:

>>> text = "your debt is 100 dollars"
>>> [f"{w} {n}" for w, n in zip(text.split(), text.split()[1:]) if w == "is" and n.isdecimal()]
['is 100']

i.e. "give me sequential pairs of words from text where the first word is is and the second word is a number".

Answered By: Samwise

The following matches any number that comes after the word "is" and only returns the number:

print(re.findall(r'biss+(d+)b', text))
Answered By: EDD
import re

text = "your debt is 100 dollars"
print(re.findall(r'iss*d+', text))

In this regex, s* matches zero or more whitespace characters and d+ matches one or more digits.

Answered By: Ake
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.