Forum Moderators: coopster

Message Too Old, No Replies

Regular expression negation

How to negate a phrase in regex?

         

frex65

1:40 pm on Feb 12, 2004 (gmt 0)

10+ Year Member



Hi all,
I'm trying to negate a phrase rather than just a single character in a regular expression. Is there a syntax for multiple character negation? For example, if 'Brenda Brown' and 'Brenda Jones' are OK, but not 'Brenda Smith'?
Regex is such a powerful tool -surely there's a multiple negation operator.
Thanks - much appreciated,
Frex

coopster

6:37 pm on Feb 14, 2004 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



Welcome to WebmasterWorld, frex65!

Well, there are a few ways to accomplish your goal, but a zero-width, negative lookahead assertion [php.net] is the tool you will more than likely end up using. A lookahead assertion is a test on the characters following the current matching point that does not actually consume any characters. And in this case, it is a negative assertion or, "don't match this":


$string = "'Brenda Brown' and 'Brenda Jones' are OK, but not 'Brenda Smith'?";
// There's a space after Brenda in the next line:
preg_match_all("/'Brenda (?!Smith').*'/Uis", $string, $matches);
print "$string<br />";
print "<pre>"; print_r($matches); print "</pre>";

Will give you this:

'Brenda Brown' and 'Brenda Jones' are OK, but not 'Brenda Smith'?
Array
(
[0] => Array
(
[0] => 'Brenda Brown'
[1] => 'Brenda Jones'
)

)

frex65

11:57 am on Feb 16, 2004 (gmt 0)

10+ Year Member



Cheers coopster, especially for that link to info on assertions. It works beautifully. Very much appreciated.