Beefy Boxes and Bandwidth Generously Provided by pair Networks
XP is just a number
 
PerlMonks  

how to use "NOT" in regex

by palkia (Monk)
on Mar 23, 2011 at 20:29 UTC ( #895118=perlquestion: print w/replies, xml ) Need Help??

palkia has asked for the wisdom of the Perl Monks concerning the following question:

Hello
I'm trying to match (for replace) a text line that doesn't start with one of two words.
The only thing about "not" I could find for replace purposes in regex was the ^abc.. syntax
which only match 1 char and never longer strings.
Is there a way to do this ?
I'm expecting something like s/ \n !($word1|$word2) .* \n / $replacement /x
or maybe something like s/ $ !($word1|$word2) .* \n / $replacement /x
or maybe even s/ ^ ($word1|$word2){0} .* \n / $replacement /x
am I close ?
There got to be a better way.
thx

Replies are listed 'Best First'.
Re: how to use "NOT" in regex
by wind (Priest) on Mar 23, 2011 at 20:33 UTC
    Use a zero width negative look-ahead assertion. perlre
    /^(?!$word1|$word2).../
    Also, you might want to escape the "words" for regex special characters using quotemeta.
    /^(?!\Q$word1\E|\Q$word2\E).../
Re: how to use "NOT" in regex
by mellon85 (Monk) on Mar 23, 2011 at 23:34 UTC

    can't you match the strings that start with those two words and then negate the condition? makes more sense to me as a regexp

    if (!/^($word1|$word2)/) { # code }

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://895118]
Approved by chrestomanci
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others romping around the Monastery: (4)
As of 2022-12-04 11:42 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found

    Notices?