3

I have to create a regex which will match anything (including line breaks) between 2 html specific comment tags. Here is an example for some html:

<!-- build-remove-start -->
<!-- bower:js -->
<script src="../bower_components/jquery/dist/jquery.js"></script>
<!-- endbower -->
<!-- build-remove-end -->

<!-- inject:vendor:js -->
<!-- endinject -->

I would like to match every thing between <!-- build-remove-start --> and <!-- build-remove-end --> not including the comment tags (I mean not to remove the comments tags, only what's inside).
I have tried:
<!-- build-remove-start -->[\s\S]<!-- build-remove-end -->
But it doesn't work. Here is a link to test the regex:
https://regex101.com/r/rV0qG2/2

3
  • 2
    Check this demo. Commented Nov 14, 2015 at 18:39
  • might i suggest actually using the DOM, which can iterate over comment nodes? Commented Nov 14, 2015 at 18:48
  • @Eevee, It is for building purposes Commented Nov 14, 2015 at 18:49

1 Answer 1

5

You need to add * after [\s\S].

/<!-- build-remove-start -->([\s\S]*?)<!-- build-remove-end -->/gmi

Also I recommend adding ? after * so it makes it lazy. This way you can have the example below, othwerise the this won't be removed line will be matched.

<!-- build-remove-start -->
//remove this
<!-- build-remove-end -->

This won't be removed

<!-- build-remove-start -->
//Remove this
<!-- build-remove-end -->
Sign up to request clarification or add additional context in comments.

9 Comments

doesn't this includes the comments tag?
Why the capture group?
You only need to replace what's inside the capture group, and not the whole match.
@MarcosCasagrande, it seems that the comments are also falls to the matching pattern, I need it to be excluded. Here is a demo of your answer regex101.com/r/rV0qG2/4
[\s\S]*? will inevitably drain the backtracking buffer limit with large HTML code and the code execution will freeze. Use the regex in my comment if you want to have the same effect but avoid backtracking issues.
|

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.