Negative Matching?

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Negative Matching?

Post by Benjamin »

Not sure what this is called. I am looking to match all files in a directory which are not one of:

.
..
.svn

I ended up approaching this by using regex that will exclude these, however I'm wondering how to write regex which will NOT match them.

Here's what I tried, it doesn't work.

Code: Select all

#^(?:[^\.]|[^\.]{2}|[^(?:svn)]).*$#
User avatar
ridgerunner
Forum Contributor
Posts: 214
Joined: Sun Jul 05, 2009 10:39 pm
Location: SLC, UT

Re: Negative Matching?

Post by ridgerunner »

Try this:

Code: Select all

if (preg_match('/^(?!\.{1,2}$|\.svn$).+$/m', $contents)) {
    # Successful match
} else {
    # Match attempt failed
}
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Re: Negative Matching?

Post by Benjamin »

Worked perfectly!
No Match .
No Match ..
No Match .svn
Match .htaccess
Match includes
Match images
User avatar
hypedupdawg
Forum Commoner
Posts: 74
Joined: Sat Apr 10, 2010 5:21 am

Re: Negative Matching?

Post by hypedupdawg »

I realise that you have found an expression that works for you - however, it may be easier to use a switch statement if you ever needed to edit it:

Code: Select all

switch ($contents)
{
case ".":
case "..":
case ".svn":
//do nothing
break;
default:
//your code here
}
By leaving out the breaks between the different cases, all the top three cases will result in the same action. The default code will then run for anything that is not those three cases.

Just another option...
Post Reply