Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Use Regular Expression to Look for the something NOT of Certain pattern

Tags:

regex

perl

Using Perl style regexp, is it possible to look for something not of certain pattern?

For example, [^abc] looks for a SINGLE CHARACTER not a nor b nor c.

But can I specify something longer than a single character?
For example, in the following string, I want to search for the first word which is not a top level domain name and contains no uppercase letter, or perhaps some more complicated rules like having 3-10 characters. In my example, this should be "abcd":

net com org edu ABCE abcdefghijklmnoparacbasd abcd
like image 692
JavaMan Avatar asked Jan 20 '23 22:01

JavaMan


2 Answers

You can do it using negative look-ahead assertions as:

^(?!(?:net|com|org|edu)$)(?!.*[A-Z])[a-z]{3,10}$

See it

Explanation:

^                   - Start anchor
$                   - End anchor
(?:net|com|org|edu) - Alternation, matches net or com or org or edu
(?!regex)           - Negative lookahead. 
                      Matches only if the string does not match the regex.

So the part (?!(?:net|com|org|edu)$) ensures that input is not one of the top level domains.

The part (?!.*[A-Z]) ensures that the input does not have a upper case letter.

The part [a-z]{3,10}$ ensures that the input is of length atleast 3 and atmost 10.

like image 167
codaddict Avatar answered Jan 25 '23 23:01

codaddict


Just use the "not match" operator: !~

So just create your expression and then see that a variable does not match it:

if ($var !~ /abc/) {
  ...
}
like image 33
ldx Avatar answered Jan 25 '23 23:01

ldx