1

I have a regex that looks like the following:

var myRegex = /%([a-z_]*)%/i

This matches any substring such as %foo% where a string is between two quotes.

What's the best way to modify this regex so that it only matches when the regex matches when % surrounds anything BUT the string foo? So it won't match %foo% but it would match %bar_% %anythingelse%?

1 Answer 1

3

You're looking for a negative lookahead here:

var myRegex = /%(?!foo%)([a-z_]*)%/i;

(?!foo%) is negative lookahead that will assert failure when we have foo% is ahead of % thus failing %foo%.

Sign up to request clarification or add additional context in comments.

5 Comments

Wouldn't this incorrectly not match %foolkajsdksad%?
@Jay No, because foo% is a string literal. There are no wildcards between foo and %
@Jay Nope, because the negative lookahead looks for foo% instead of foo
what about %alskjdfoo%?
So I tested it out, but I'm not really sure why it should match that string haha

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.