igorGIS
igorGIS

Reputation: 1946

How to prevent a regex match if a certain substring is present within?

HTML comments may use inline JavaScript as special blocks for old browsers that don't support JS code. These blocks look like this:

<!--
some js code
//-->

I want to distinguish 'true' html comments from such in JS code. I've written this regex:

/<!--[^//]*?-->/g

So I want to exclude matches with a double slash inside, but the regex regards // as a character set of / and /, not as entire double slash //. What can I do?

Upvotes: 2

Views: 350

Answers (1)

Tim Pietzcker
Tim Pietzcker

Reputation: 336158

Character classes, as you noted, only match a single character, so you can't use them here. But you can make use of negative lookahead assertions:

/<!--(?:(?!//)[\s\S])*-->/g

(assuming this is JavaScript).

Explanation:

<!--     # Match <!--
(?:      # Try to match...
 (?!//)  #  (asserting that there is no // ahead)
 [\s\S]  #  any character (including newlines)
)*       # ...any number of times.
-->      # Match -->

Upvotes: 5

Related Questions