views:

74

answers:

2

I am trying to use this regex (JS):

/\/\*(.*)\*\//g

To replace

/*
sdandsads
*/

with nothing.

But it is not working! Why? o_O

+2  A: 
Gaby
There's no `s` (single-line) mode in JavaScript, and `(\s|.)` courts catastrophic backtracking. The standard way to match anything-including-newlines in JS is `[\S\s]`.
Alan Moore
@alan, any links about the `\s|.` backtracking ? would like to learn more about it..
Gaby
Erik Corry explained it well here: http://stackoverflow.com/questions/2407870/javascript-regex-hangs-using-v8/2408599#2408599 For a more general discussion of catastrophic backtracking, see http://www.regular-expressions.info/catastrophic.html
Alan Moore
wow, pretty obvious once you consider that regexp has to be applied somehow, and it is not just a rule and a result :) thanks for the links @Alan
Gaby
+3  A: 

Two problems:

  1. In javascript, there's no dotall modifier. You'll have to use a hack to allow matching newlines, such as using [^].
  2. You're using greedy matching. If there are multiple comments in your input, everything between them will be eaten.

Solution:

/\/\*[^]*?\*\//g

Example:

> '/*abc\ncde*/qqq/*iop\n\njj*/'.replace(/\/\*[^]*?\*\//g, '')
qqq
Max Shawabkeh
+1, altered to not greedy..
Gaby