views:

66

answers:

1

Hi Guys,

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

+1  A: 

. 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

Philipp G
IMO, `--` is more to the point than `-{2}`, and `(.|\s)` could be replaced by `[\s\S]`. Also, `!` and `-` don't need escaping.
Bart Kiers
Yes you are right, fixed it.
Philipp G
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.
MikeD
@Philipp, 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.
Bart Kiers
@Bart K: Ok! You live and learn. :) Thanks.
Philipp G