27

I'm trying to match a string (using a Perl regex) only if it doesn't start with "abc:" or "defg:", but I can't seem to find out how. I've tried something like

^(?:(?!abc:)|(?!defg:))
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
tobbo
  • 407
  • 1
  • 4
  • 7
  • that asks for any string that doesn't start abc: *or* doesn't start defg:, which is any string – ysth Nov 27 '14 at 23:47

7 Answers7

38

Lookahead (?=foo), (?!foo) and lookbehind (?<=foo), (?<!foo) do not consume any characters.

You can do multiple assertions:

^(?!abc:)(?!defg:)

or:

^(?!defg:)(?!abc:)

...and the order does not make a difference.


You can use De Morgan (as other answers do):

(NOT A) AND (NOT B) <=> NOT (A OR B) 

...and shorten the expression to:

^(?!abc:|defg:)
Neuron
  • 5,141
  • 5
  • 38
  • 59
Stephan Stamm
  • 1,063
  • 10
  • 13
9

Try doing this:

^(?!(?:abc|defg):)
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223
2

Use this regex:

^(?!abc:|defg:)\s*\w+

This will avoid line start with "abc:" and "defg:" as you want.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
AJP
  • 43
  • 1
  • 9
1

… or we could have dropped the alternation from the original expression:

^(?:(?!abc:)(?!defg:))
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Abecee
  • 2,365
  • 2
  • 12
  • 20
0
^(?:(?!abc:|defg:).)*$

Try this. See the demo at http://regex101.com/r/hQ9xT1/18.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
vks
  • 67,027
  • 10
  • 91
  • 124
0

This will do the task:

^(?!(defg|abc):).*
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
blackSmith
  • 3,054
  • 1
  • 20
  • 37
0

Could you please try this:

use strict;
use warnings;
use Cwd;

while(<DATA>)
{
    my $line=$_;
    print $line unless($line=~m/^(abc|defg*)/m);
}

__DATA__
ebc this is testing ebc
dbc this is testing dbc
defg this is testing defg
abc this is testing abc
defg this is testing defg
ssr1012
  • 2,573
  • 1
  • 18
  • 30