guest1
guest1

Reputation: 53

Regular Expression, greedy over |

for some weeks im working with regular expressions in php. Now my question: Is there any way, to make the RegEx greedy over | ?

for example subject: 012345abcdefghijklm

pattern: /(abcde|abcdefghi)/ will extract abcde, although abcdefghi is the greedier match.

The only way i found, is to sort the RegEx by the highest length of possibly matches

Thanks

Upvotes: 4

Views: 122

Answers (3)

HMK
HMK

Reputation: 574

Not a perfect solution. But it provides alternative other than the sorting one:

(abcde(?!fghi)|abcdefghi)

Upvotes: 0

Andrew Moore
Andrew Moore

Reputation: 95334

There is no way other than reordering the elements or by adding an optional non-capture group.

Regular Expression engines are eager. Because of the way the Alternation meta-character works (|), the first possible match exits the alternation clause.

Either re-order the possible choices (/(abcdefghi|abcde)/) or use an optional non-capture group (/(abcde(?:fghi)?)/).

Upvotes: 2

Andie2302
Andie2302

Reputation: 4887

Here you should use:

abcde(?:fghi)?

Upvotes: 0

Related Questions