Variable Length Appearance

Is there an elegant solution for creating a regex with a variable size like this?

/(?<=eat_(apple|pear|orange)_)today|yesterday/g; 

Perl seems to have a very impressive regex engine, and the variable lookbehind length would be very interesting. Is there a way to make it work, or should I forget this bad idea?

+7
regex perl
source share
3 answers

Use \K as a special case.

This is the variable length of the lookbehind positive statement:

 /eat_(?:apple|pear|orange)_\Ktoday|yesterday/g 

Alternatively, you can list your lookbehind statements separately:

 /(?:(?<=eat_apple_)|(?<=eat_pear_)|(?<=eat_orange_))today|yesterday/g 

However, I would suggest that this was a rare problem that could potentially use this function, but could not rethink the use of a combination of other more general regular expression functions.

In other words, if you are stuck with a specific problem, feel free to share it here, and I'm sure someone could come up with a different (possibly better) approach.

+8
source share

You can use look-ahead instead of look-behind:

 /(?:eat_(apple|pear|orange)_)(?=today|yesterday)/g 

and in general, there is an alternative way to describe things that naively seem to require a look.

+3
source share

What about:

 (?:(?<=eat_apple_)|(?<=eat_pear_)|(?<=eat_orange_))(today|yesterday) 

A little uggly, but it works.

+3
source share

All Articles