Reputation:
I have written a regular expression but am confused on how to inject a lookaround into it.
I have the following strings:
myName is myLastName
yourName is yourLastName
and I want, using negative lookbehind, to make it only match the one which does not include myName. myName is not surely in the beginning of the sentence, it might just be in the middle of another longer phrase. Up to here, I have written the following match reg exp which match both of the sentences (naturally), but I want to add a condition using negative look behind:
(([a-zA-Z]*)( *)(is)( *)([a-zA-Z]*))
Upvotes: 1
Views: 251
Reputation: 785156
If you want to use negative lookbehind, then following regex should work:
([a-zA-Z]+)(?<!\bmyName\b) +is +([a-zA-Z]+)
(?<!\bmyName\b)
is a negative lookbehind that doesn't match a word that is preceded by literal string myName
. \b
is for word boundary.
Upvotes: 1
Reputation: 76656
If you're just trying to match the string which doesn't contain the word myName
, then you can use the following regex with a negative lookahead:
/^(?!myName).*$/
Explanation:
/
- starting delimiter
^
- assert position at the beginning of the string(?!
- negative lookaheadmyName
- matches the characters myName
literally)
- end of lookahead.*
- match any character (except newline) zero or more times$
- assert position at end of the string/
- ending delimiterEssentially, the above regex will match any string that doesn't contain the word myName
(case-sensitive).
Test case:
$arr =['myName is myLastName','yourName is yourLastName'];
foreach ($arr as $str) {
if (preg_match('/^(?!myName).*$/', $str, $matches)) {
echo 'Match', PHP_EOL;
} else {
echo 'No match', PHP_EOL;
}
}
Output:
No match
Match
Upvotes: 0