0

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!

4

2 回答 2

4

只需使用?量词使第二部分成为可选:-

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

使用(?:.*\:\s(\d*))?使模式.*\:\s(\d*)可选。作为?手段匹配0 or 1

请注意,我使用了一个non-capturing组,用于额外的分组以使其成为可选。通过使用它,您的捕获组编号不会与当前的编号不同。因为,在捕获的组计数中不考虑非捕获组-事物。(?:...)

于 2013-01-28T20:23:10.357 回答
0

我认为这应该有效

r'.*?(\d+)\s(good|bad)[^\d]*(\d*)'
于 2013-01-28T20:50:57.753 回答