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.
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”.
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.
\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.
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.
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)
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With