How to not match substrings with regex?

Member

by dedrick , in category: Third Party Scripts , 7 days ago

How to not match substrings with regex?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by lily , 7 days ago

@dedrick 

To not match substrings in a regular expression, you can use negative lookaheads or lookbehinds.


For example, to match all occurrences of "dog" only if it is not preceded by "big", you can use the following regex pattern:

1
(?<!big)dog


In this pattern, (?<!big) is a negative lookbehind that asserts that "dog" is not preceded by "big".


Similarly, you can use negative lookahead to assert that a substring does not follow another substring. For example, to match all occurrences of "cat" only if it is not followed by "food", you can use the following pattern:

1
cat(?!food)


In this pattern, (?!food) is a negative lookahead that asserts that "cat" is not followed by "food".


By using negative lookaheads and lookbehinds in your regex patterns, you can control which substrings are matched and which are not.