ExReg has asked for the wisdom of the Perl Monks concerning the following question:
but notmaybe some stuff foo maybe some more stuff;
This looks like an appropriate place to use a negative lookbehind assertion. I have not found the right form yet. Experimenting, I have tried// maybe some stuff foo maybe some more stuff;
$a="abcdefghijklm"; 1 print "match" if ( $a =~ /(?<!cde).*?jkl/ ); # match because a do +es not match cde, then bcdefghi follows, then jkl matches? 2 print "match" if ( $a =~ /(?<=cde).*?jkl/ ); # match because cde +matches then fgh follws, then jkl matches $a="xyzfghijklm"; 1 print "match" if ( $a =~ /(?<!cde).*?jkl/ ); # match because cde +is not before jkl, then jkl matches 2 print "match" if ( $a =~ /(?<=cde).*?jkl/ ); # no match because c +de is not before jkl
I am looking for a regex that will not match abcdefghijklm because cde precedes jkl, but would match xyzfghijkl. I would have thought that something like the first one above would be what I wanted.
If I wanted it to not match when jkl must not be preceded by only c, the answer is easy: ^[^c]*jkl. But I have multiple character cde things I must exclude.
I am guessing that what I am looking for will have a (?<!cde) and then a jkl in it.
One trick I used several years ago, seems to work here. Since you cannot do variable length lookbehinds, I can reverse the strings and then do variable length lookaheads. i.e.
$a = "mlkjihgfedcba"; print "match" if ( $a =~ /lkj(?!.*?edc/ ); # no match because edc D +OES follow lkj. This is what is desired. (It does not match in the un +reversed when cde precedes jkl) $a = "mlkjihgfzyx"; print "match" if ( $a =~ /lkj(?!.*?edc/ ); # match because edc does + not follow lkj. Again, this is what I want. ( It does match jkl in t +he unreversed when not preceded by cde)
Is there another way?
I am guessing this is one of those areas where regexes come up short. I just learned about (?{ }) and (??{ }), but don't fully understand them yet. Where is a good place to learn advanced regex aside from perlre and Friedl?
I am limited to perl 5.6, if that makes a difference. I cannot use CPAN or any other libraries.
If this question seems disjoint, it is because my brain stores in hashes instead of sorted arrays.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re: Capture uncommented keywords
by atcroft (Abbot) on Jul 27, 2015 at 20:59 UTC | |
by ExReg (Priest) on Jul 27, 2015 at 21:23 UTC | |
by ExReg (Priest) on Jul 27, 2015 at 21:12 UTC | |
|
Re: Capture uncommented keywords
by afoken (Chancellor) on Jul 28, 2015 at 14:41 UTC | |
by ExReg (Priest) on Jul 28, 2015 at 18:23 UTC |