coldheart
coldheart

Reputation: 25

Python using AND with regex

So I have looked around the internet for like 20 minutes and I haven't been able to figure it out. Is it possible to use AND in regex, or something similar (I've just started learning about regex)?

For example, I have the string "finksdssfsk32residogs" and I want to get the output: "32 dogs". I've tried using re.search, re.match, and re.findall but I haven't had any luck. I've tried things like:

re.findall(r"(\d{2})(dogs)", str)
re.search(r"(\d{2})(dogs)", str)

And I've tried a few combinations of each. And I know I can do this with multiple lines but the goal is to get "32 dogs" from "finksdssfsk32residogs" with only one line. Any help is appreciated, thanks.

Upvotes: 1

Views: 29

Answers (1)

kojiro
kojiro

Reputation: 77137

You've almost got it. You just need some space between the numbers and the dogs.

Can you just match anything? How about (\d{2}).*(dogs)? Then you can replace the middle part with a space using join:

>>> print(' '.join(re.search(r'(\d{2}).*(dogs)', 'finksdssfsk32residogs').groups()))
32 dogs

Upvotes: 1

Related Questions