Using the 'exclusion' character [^x] for a full word

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

Moderator: General Moderators

Post Reply
CallumD
Forum Newbie
Posts: 11
Joined: Wed May 03, 2006 12:36 am

Using the 'exclusion' character [^x] for a full word

Post by CallumD »

Hi,

Is there a way to use the "all characters except for" character in a Regex, but rather than exclude individual characters, exclude full words.

For example, [^269] will pick up all characters except for the number 2, 6, and 9.

But what if I wanted to exclude a word? For example [^"hello"], which will detect *anything* other than the word "hello".

Can it be done?

Thanks.

Callum.
User avatar
CoderGoblin
DevNet Resident
Posts: 1425
Joined: Tue Mar 16, 2004 10:03 am
Location: Aachen, Germany

Post by CoderGoblin »

Can't think immediately of how to do it but personally I would use preg_replace to simply find those words and automatically remove them rather than find all words not matching. Then process the string as you want.
User avatar
bokehman
Forum Regular
Posts: 509
Joined: Wed May 11, 2005 2:33 am
Location: Alicante (Spain)

Post by bokehman »

You need a negative lookahead (zero width assertion). The follow sub-expession matches (not captures) any string that starts on a word boundary, ends on a word boundry and only contains the lowercase characters a-z. It is preceeded by a negative lookahead which returns false if the word is a lowercase "hello".

Code: Select all

(?:(?!\bhello\b)\b[a-z]+\b)
Post Reply