How to match to the longest pattern

Viewed 61

How do I modify the following to match abbb instead of just stop at ab?

>>> re.match('ab|abb|abbb', 'abbb')
<re.Match object; span=(0, 2), match='ab'>
2 Answers

You could use:

re.match('ab(b(b)?)?', 'abbb')
<_sre.SRE_Match object; span=(0, 4), match='abbb'>

The ? here means that the preceding item is optional, but it is greedy, so the item will be included in the match if possible (the lazy equivalent is ??).

The inner parentheses are not required here (because they enclose only a single character) but are included to make it more obvious you might extend it to a longer sequence. All that you strictly need is:

re.match('ab(bb?)?', 'abbb')

The above does not depend on the fact that the b is repeated in the pattern, for example you could similarly have:

re.match('ab(c(d)?)?', 'abcd')
<_sre.SRE_Match object; span=(0, 4), match='abcd'>

However, if in fact you do not require the generality of this approach, then you could instead use the following to match a followed by 1 to 3 bs:

re.match('ab{1,3}', 'abbb')
<_sre.SRE_Match object; span=(0, 4), match='abbb'>

Again, the {1,3} quantifier is greedy so will match as many as possible. (The lazy equivalent is {1,3}?.)

It depends on the order of your patterns. Try

re.match('abbb|abb|ab', 'abbb')
Related