Negation of RegEx

A

Andreas Hochsteger

Hi,

is it possible to construct a single regular expression which matches
everything except strings which start with a certain string?
I need it for matching Paths and want to exclude certain directories.

Example:
Match all paths not starting with /forms/ or /users/:
/index.php and /contact/index.php should match, but not
/forms/contact.php as well es /users/login.php.

Any ideas?
Please have in mind, that I have to use the regular expression in a
configuration file so it's not possible to do the negation from within
a programming language.

Thanks,
Andreas.
 
R

Randal L. Schwartz

Andreas> is it possible to construct a single regular expression which matches
Andreas> everything except strings which start with a certain string?

The regex

/^(?!FOO)/

matches everything except lines that start with FOO.

print "Just another Perl hacker,"; # and the first one, at that
 
E

Eric Schwartz

is it possible to construct a single regular expression which matches
everything except strings which start with a certain string?
I need it for matching Paths and want to exclude certain directories.

Randal's answer answers your specific question, but you can also solve
the problem in other ways:

if your code looks like:

if (/regex matching items you like/) {
....
}

you can also write it like this:

unless (/regex matching items you don't like/) {
....
}

or

unless ($item !~ /regex matching items you don't like/) {
....
}

But the last example uses !~, which is considered confusing by some,
so I don't recommend it.

-=Eric
 
R

Randal L. Schwartz

Eric> you can also write it like this:

Eric> unless (/regex matching items you don't like/) {
Eric> ...
Eric> }

Yes, but Original Poster said:

OP> Please have in mind, that I have to use the regular expression in
OP> a configuration file so it's not possible to do the negation from
OP> within a programming language.

Hence, non-solution, even from a Schwartz. :)

print "Just another Perl hacker,"; # the first!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top