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']
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".
The following matches any number that comes after the word "is" and only returns the number:
print(re.findall(r'biss+(d+)b', text))
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.
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']
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".
The following matches any number that comes after the word "is" and only returns the number:
print(re.findall(r'biss+(d+)b', text))
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.