1

I have a regex that I want to match a certain pattern. However, I don't want it to match that pattern if it exists between HTML comment blocks

What I have currently is:

(?<!<!--)pattern(?!-->)

However that only works when the pattern is exactly between comment blocks but not in the case of something like:

<!-- foo pattern -->

But if I do:

(?<!<!--.*)pattern(?!-->)

then this case doesn't work:

<!-- some commented out stuff --> pattern

I think if I could express (everything except -->)*? within the negative look behind it would work but I'm unsure of the proper syntax or if that's allowed.

5
  • (?<!<!--[^<>]*)pattern(?![^<>]*-->) might work then. What you ask for is (?<!(?:(?!<!--|-->).)*)pattern(?!(?:(?!<!--|-->).)*-->) Commented Jun 14, 2019 at 21:32
  • 1
    Use a real HTML parser. See also. Commented Jun 14, 2019 at 21:52
  • When you say between comment blocks, if you have 400 comment blocks or 2, all it takes is to have a comment block at the top, and one at the bottom. Commented Jun 14, 2019 at 22:04
  • No matter how you try, there is only one way to do this, replace the first and last comment, and everything between with nothing, then try a new regex with your pattern on what's left. Commented Jun 14, 2019 at 22:07
  • 1
    You can't just say (?:<!--comment-->.*<!--comment-->)?.*?pattern it finds pattern no matter what. You could match both, to move past comments like this (?:<!--comment-->.*<!--comment-->)|(pattern) then see if group 1 matched. It's the only way. Commented Jun 14, 2019 at 22:12

1 Answer 1

0

My guess is that, your original expression is just fine with maybe a bit modification, we might want to have an expression similar to:

(?<=<!--).*pattern.*(?=-->)

Demo

and if we wish to capture or not-capture anything around pattern these might be of interest:

(?<=<!--).*(pattern).*(?=-->)
(?<=<!--)(.*pattern.*)(?=-->)
(?<=<!--)(.*)(pattern)(.*)(?=-->)
(?<=<!--)(?:.*)(pattern)(?:.*)(?=-->)
Sign up to request clarification or add additional context in comments.

Comments

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.