52

I have this regex:

if($string =~ m/^(Clinton|[^Bush]|Reagan)/i)
  {print "$string\n"};

I want to match with Clinton and Reagan, but not Bush.

It's not working.

3
  • 3
    what if the string starts with none of these words?
    – mirod
    Jun 15, 2011 at 16:53
  • 8
    Wouldn't matching Clinton or Reagan already mean you're not matching for Bush? Or not matching for Bush mean you will match Clinton or Reagan?
    – NorthGuard
    Jun 15, 2011 at 17:04
  • 2
    Sometimes the best solution is to eliminate complexity by splitting it into two regular expressions. One positive, one negative.
    – DavidO
    Jun 15, 2011 at 17:21

5 Answers 5

152

Your regex does not work because [] defines a character class, but what you want is a lookahead:

(?=) - Positive look ahead assertion foo(?=bar) matches foo when followed by bar
(?!) - Negative look ahead assertion foo(?!bar) matches foo when not followed by bar
(?<=) - Positive look behind assertion (?<=foo)bar matches bar when preceded by foo
(?<!) - Negative look behind assertion (?<!foo)bar matches bar when NOT preceded by foo
(?>) - Once-only subpatterns (?>\d+)bar Performance enhancing when bar not present
(?(x)) - Conditional subpatterns
(?(3)foo|fu)bar - Matches foo if 3rd subpattern has matched, fu if not
(?#) - Comment (?# Pattern does x y or z)

So try: (?!bush)

2
34

Sample text:

Clinton said
Bush used crayons
Reagan forgot

Just omitting a Bush match:

$ perl -ne 'print if /^(Clinton|Reagan)/' textfile
Clinton said
Reagan forgot

Or if you really want to specify:

$ perl -ne 'print if /^(?!Bush)(Clinton|Reagan)/' textfile
Clinton said
Reagan forgot
2
  • 4
    best sample text ever Jun 20, 2017 at 15:50
  • 12
    No idea why no one has mentioned it but (?!Bush) negative lookahead is completely redundant in the ^(?!Bush)(Clinton|Reagan) pattern because neither Clinton nor Reagan start with Bush. Jul 14, 2017 at 21:03
22

Your regex says the following:

/^         - if the line starts with
(          - start a capture group
Clinton|   - "Clinton" 
|          - or
[^Bush]    - Any single character except "B", "u", "s" or "h"
|          - or
Reagan)   - "Reagan". End capture group.
/i         - Make matches case-insensitive 

So, in other words, your middle part of the regex is screwing you up. As it is a "catch-all" kind of group, it will allow any line that does not begin with any of the upper or lower case letters in "Bush". For example, these lines would match your regex:

Our president, George Bush
In the news today, pigs can fly
012-3123 33

You either make a negative look-ahead, as suggested earlier, or you simply make two regexes:

if( ($string =~ m/^(Clinton|Reagan)/i) and
    ($string !~ m/^Bush/i) ) {
   print "$string\n";
}

As mirod has pointed out in the comments, the second check is quite unnecessary when using the caret (^) to match only beginning of lines, as lines that begin with "Clinton" or "Reagan" could never begin with "Bush".

However, it would be valid without the carets.

4
  • 1
    the second part of your test is useless: if the string matches Clinton or Reagan, then it doesn't match Bush.
    – mirod
    Jun 15, 2011 at 18:11
  • @mirod That's true, now that you mention it. It was more of an example than a true working regex. I'll add a note about that, thanks for spotting it.
    – TLP
    Jun 15, 2011 at 19:26
  • [^Bush] doesn't mean any single character except B, u, s or h. The ^ sign isn't a negation metacharacter. It implies that the following should occur at the beginning of the tested string. And since a ^ was already used, I have no idea if this has any further effect, but certainly not negation :)
    – yair
    Dec 26, 2017 at 9:41
  • 3
    @yair ^ in general does refer to the beginning of the string. However, within a character class it does indeed negate the class. So, [Bush] matches any of the 4 characters B, u, s, or h, and [^Bush] matches any character other than those 4. Mar 30, 2018 at 20:13
3

What's wrong with using two regexs (or three)? This makes your intentions more clear and may even improve your performance:

if ($string =~ /^(Clinton|Reagan)/i && $string !~ /Bush/i) { ... }

if (($string =~ /^Clinton/i || $string =~ /^Reagan/i)
        && $string !~ /Bush/i) {
    print "$string\n"
}
2
  • see my comment on TLP's answer, the second part of the test is useless
    – mirod
    Jun 15, 2011 at 18:13
  • I'll add that I've seen scenarios where adding additional regular expressions is not the right answer, where the regular expression is assumed to include all the logic required to match a record (ie: looping through an array of regular expressions). On the other hand the lookahead is redundant in this example. Jun 16, 2011 at 21:13
2

If my understanding is correct then you want to match any line which has Clinton and Reagan, in any order, but not Bush. As suggested by Stuck, here is a version with lookahead assertions:

#!/usr/bin/perl

use strict;
use warnings;

my $regex = qr/
    (?=.*clinton)  
    (?!.*bush) 
    .*reagan       
    /ix;

while (<DATA>) {
    chomp;
    next unless (/$regex/);
    print $_, "\n";
}


__DATA__
shouldn't match - reagan came first, then clinton, finally bush
first match - first two: reagan and clinton
second match - first two reverse: clinton and reagan
shouldn't match - last two: clinton and bush
shouldn't match - reverse: bush and clinton
shouldn't match - and then came obama, along comes mary
shouldn't match - to clinton with perl

Results

first match - first two: reagan and clinton
second match - first two reverse: clinton and reagan

as desired it matches any line which has Reagan and Clinton in any order.

You may want to try reading how lookahead assertions work with examples at http://www252.pair.com/comdog/mastering_perl/Chapters/02.advanced_regular_expressions.html

they are very tasty :)

1
  • Sorry, seems 252 URL is down. May 5, 2020 at 6:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.