Hi,
every now and then I stumble upon the question of how to match something that doesn't match something else.
I.e. some expression in the sense of [^...]* for a general given regex $match.
The best I got so far is:
my $does_not_match = qr{((?:.*?(?=$match))|(?:(?:.(?!$match))*))};
The first branch matches a substring up to the given regex $match if there is a match and the second branch matches the whole string if there is no match.
Both fail in the opposite case. (The second branch by missing the last character.)
Does anybody know something simpler?
Or do you see any issues with the given regex?
Here is a small example:
#!/usr/bin/perl
use Test2::V0;
sub do_not_match {
my $pat = shift;
return qr{(?:.*?(?=$pat))|(?:(?:.(?!$pat))*)};
}
my $re = do_not_match(qr{\b[aeiou][a-z]*ion\b});
is [/($re)/], ['stimulated '], 'matches prefix'
for 'stimulated emission of radiation';
is [/($re)/], ['electron transition'],'no match'
for 'electron transition';
is [/($re)/], [''], 'matches empty prefix'
for 'absorbtion of photons';
is [/($re)/], ['light '], 'matches not greedy'
for 'light amplification by stimulated emission of radiation';
is [/($re)\bimpact/], ['electron '], 'gives characters back'
for 'electron impact ionization';
done_testing;
I might put this into an extension module for Regexp::Common, but I'm not sure if this makes sense at all.
And what would a proper naming be? Maybe something like:
use Regexp::Common 'do_not_match';
my $re = $RE{do_not}{-match => 'something'}
Your opinions?
-jo
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.