Frank Epps
Frank Epps

Reputation: 580

Lookbehind in python

Suppose I have:

string = "2 dogs. 4 cats. 9 horses. 7 goats"

I want to match every word that precedes a number.

I tried:

matches = re.search(r"(?<=\d+) \w+", string)

but it isn't working.

Upvotes: 0

Views: 88

Answers (1)

aemdy
aemdy

Reputation: 3802

>>> s = "2 dogs. 4 cats. horses. 7 goats"
>>> import re
>>> re.findall(r'\d+\s(\w+)', s)
['dogs', 'cats', 'goats']

Upvotes: 4

Related Questions