1

I am using below regular expression to remove comments from string

<\!{1}\-{2}(.*?)\-{2}\s*>

This is working fine except for mult-iline string

var search = '<\!{1}\-{2}(.*?)\-{2}\s*>';

  var re = new RegExp(search, "gm");

  var subject = <multi-line string>;
  result = subject.replace(re, '');

what should I do to get it working with multiline strings

2
  • 2
    < !-- -- > ← This is not a comment. Commented Jul 9, 2010 at 13:10
  • 2
    A bad idea. Consider: var s = "<!--"; a = b + c; s = "-->"; Commented Jul 9, 2010 at 13:18

1 Answer 1

2

. does not allow linebreaks.

This one should work:

^(<\!\-{2})((.|\s)*?)\-{2}>$

Fix:

<!--[\S\s]*?-->

I removed the \s at the beginning and the end of the expression and added it in the middle so multiline-comments are allowed.

But you shoud have a look at BartKs comment ;)

regards

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

3 Comments

IMO, -- is more to the point than -{2}, and (.|\s) could be replaced by [\s\S]. Also, ! and - don't need escaping.
For the meat of the expression, wouldn't we just want ([^\-]*), question mark. (I would have felt bad ending this comment with a '?' when it could easily be construed as part of the regex, which is not the case.) Edit: It would fail on <!-- - -->, I haven't had my morning coffee.
I made a slight edit: the class [\S|\s] does not need to contain the | (OR): inside a character class, | just matches the literal "|". Also, The regex doesn't need to be anchored with ^ and $ and [\s\S] does not need to be grouped by parenthesis. But @Sourabh should be aware that replacing comments like that could result in unexpected behavior as I commented under his question.

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.