Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Negative regex for Perl string pattern match

Tags:

regex

perl

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.

like image 374
joe Avatar asked Jun 15 '11 16:06

joe


People also ask

What is \d in Perl regex?

The Special Character Classes in Perl are as follows: Digit \d[0-9]: The \d is used to match any digit character and its equivalent to [0-9]. In the regex /\d/ will match a single digit. The \d is standardized to “digit”.

How do I match a pattern in Perl?

m operator in Perl is used to match a pattern within the given text. The string passed to m operator can be enclosed within any character which will be used as a delimiter to regular expressions.

What is \b in Perl regex?

\B is a zero-width non-word boundary. Specifically: Matches at the position between two word characters (i.e the position between \w\w) as well as at the position between two non-word characters (i.e. \W\W). Example: \B.\B matches b in abc. See regular-expressions.info for more great regex info.

How do you use negation in regex?

Similarly, the negation variant of the character class is defined as "[^ ]" (with ^ within the square braces), it matches a single character which is not in the specified or set of possible characters. For example the regular expression [^abc] matches a single character except a or, b or, c.


2 Answers

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)

like image 174
Stuck Avatar answered Sep 28 '22 01:09

Stuck


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 
like image 27
Demosthenex Avatar answered Sep 28 '22 01:09

Demosthenex