Nicolas Hung
Nicolas Hung

Reputation: 603

Python Regex matching with or without

This is my expression:

r'.*?(\d*)\s(good|bad).*\:\s(\d*)'`

The strings:

Hello 30 good. found: 50.

Hello 10 bad.

My question is: My expression matches (30, good and 50) for the first string, but how do I get it to match (10, bad) for the second one?

As of now, the expression is omitting the second line since it does not fit the description

thanks!

Upvotes: 0

Views: 72

Answers (2)

Ersin
Ersin

Reputation: 66

I think this should work

r'.*?(\d+)\s(good|bad)[^\d]*(\d*)'

Upvotes: 0

Rohit Jain
Rohit Jain

Reputation: 213331

Just make the second part optional by using ? quantifier: -

r'.*?(\d*)\s(good|bad)(?:.*\:\s(\d*))?'

Using (?:.*\:\s(\d*))? makes the pattern .*\:\s(\d*) optional. As ? means match 0 or 1.

Note that, I have used a non-capturing group, for that extra grouping to make it optional. By using this, your capturing groups numbering would not be altered from what the current one is. Because, a non-capturing group - the (?:...) thing, is not considered in the captured group count.

Upvotes: 4

Related Questions