Search code examples
regexregex-lookaroundsregex-negation

How to negate a substring only in a certain section of the string with regex?


I'm trying to achieve the following thing: I want to negate the appearance of the substring '::' but only in a certain section of the string. For example:

a<anyStringWithout'::'>b<anyStringAlsoWith'::'>

I tried to do that with negative lookahead like this:

a(?!.*::).*b

But occurrences of '::' after 'b' also make the string to unmatch, for example: 'acb::'

Is there a way to achieve what I want with regex?

Thanks in advance!


Solution

  • You can use

    a(?:(?!a|b|::).)*b
    

    This matches any string that starts with a pattern, then matches any char that does not start the a, b and :: patterns, zero or more times, up to the b pattern.

    Details

    • a - an a pattern
    • (?: - start of a non-capturing group:
      • (?!a|b|::) - a negative lookahead that fails the match if there is a, b or :: immediately to the right of the current location
      • . - any char but a line break char
    • )* - zero or more times
    • b - a b pattern.