I am trying to write a regular expression in PERL that will pick the shortest match. I have written one that will identify many matches, but I need to be able to pick the shortest of all the matches.
Let say I have the following text:
$text = "blah BEG blah blah blah END blah blah BEG blah END blah BEG blah blah END";
I can use this regular expression to identify the three cases that begin with BEG and end with END without either BEG or END being between BEG and END.
/(BEG(?:(?!BEG|END).)*END)/
It captures the three cases.
BEG blah blah blah END
BEG blah END
BEG blah blah END
I want to match only the second one since it is shortest of the three.
I have considered pulling all matches to an array and identifying the shortest element of the array.
Is there an easier way to incorporate this into the regular expression?
Thanks in advance for your thoughts and help!
It can be done entirely in a Perl regular expression (with the help of embedded Perl code), but it would be silly unless you absolutely require that.