8

I am trying to use this regex (JS):

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

To replace

/*
sdandsads
*/

with nothing.

But it is not working! Why? o_O

tangens
  • 39,095
  • 19
  • 120
  • 139

2 Answers2

17

the dot catches everything except newlines..( if the dotall is false )

so either use the dotall ( as mentioned in other answers/comments this is not supported in javascript, but i will leave it here for reference )

/\/\*(.*)\*\//gs

or add the whitespace chars \s in your expressions

/\/\*((\s|.)*?)\*\//g

Alan mentioned in his comment a bad performance from the answer i gave so use the following instead.. ( which translates to everything whitespace and everything non whitespace, so everything.. )

/\/\*([\s\S]*?)\*\//g
Gabriele Petrioli
  • 191,379
  • 34
  • 261
  • 317
  • 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 Mar 17 '10 at 01:58
  • @alan, any links about the `\s|.` backtracking ? would like to learn more about it.. – Gabriele Petrioli Mar 17 '10 at 02:35
  • 1
    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 Mar 17 '10 at 13:55
  • 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 – Gabriele Petrioli Mar 17 '10 at 14:25
  • What about `/* ... ` ? – Ivan Black Aug 30 '14 at 21:26
  • 1
    @IvanBlack this would surely not be a comment. A compiler or an interpreter would complain about a syntax error. – nalply Dec 25 '19 at 06:48
  • 1
    For reference, dotall support was added in ECMAScript 2022. – Arnauld Mar 17 '21 at 10:08
7

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
  • 37,799
  • 10
  • 82
  • 91
  • In truth the correct is: `/\/\*[^]*?\*+\//g`. Missing the `+` after the `\*`. It could also be solved like this: `/\/\*.+?\*+\//gs`. The JS now supports the `s` flag in regular expressions that allows `.` to match newline characters. Thanks so much. – rplaurindo Nov 02 '21 at 12:05