Page 1 of 1

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

Posted: Tue Oct 10, 2006 9:44 pm
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.

Posted: Wed Oct 11, 2006 3:07 am
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.

Posted: Wed Oct 11, 2006 7:14 am
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)