Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to comment a block containing regexp

Tags:

javascript

Do you know if there is a clever way to comment a block of code containing a regexp that contains */?

For instance I found myself commenting a block containing this instruction:

...

messageParser.run('messageFetched',/.*/);

...

But if I comment the block:

/*

messageParser.run('messageFetched',/.*/);

*/

then javascript interpret the regexp as comment closing and cannot parse the file. I tryied to put // in front of the offending line, but it doesn't help, and I don't want to comment every single line in the block, nor alter the regexp stuff.

There is a clever way to do this?

like image 531
Andrea Parodi Avatar asked Oct 12 '13 18:10

Andrea Parodi


3 Answers

Modify your regexp to /(.*)/:

messageParser.run('messageFetched',/(.*)/);

/*
messageParser.run('messageFetched',/(.*)/);
*/
like image 122
u_mulder Avatar answered Sep 19 '22 07:09

u_mulder


My "clever" way to do this...

Move your code in to a function, like this:

function mP () {
   messageParser.run('messageFetched',/.*/);
}

You can then use

/*
mP();
*/

Basically, it moves your regex out of the way, so that you use block comments freely without having to modify the regex code.

like image 24
Charlie74 Avatar answered Sep 20 '22 07:09

Charlie74


I know I'm late since a best answer has already been chosen, but since you were looking for a "clever trick," I would suggest ending with an empty non-capturing group:

/.*(?:)/

which is equivalent to:

/.*/

It's the most convenient if you don't want to have to change any code. (e.g. via refactoring or as a side effect of introducing a capturing group.) It's also semantically the same (introducing a capturing group would not be, and it could result in logic needing to be rewritten) and has fewer negative performance implications compared to function proxying.

The official ECMAScript specification (which the JavaScript language is based on) actually recommends using an empty non-capturing group /(?:)/ to represent an "empty" regular expression.

like image 33
JSPP Avatar answered Sep 22 '22 07:09

JSPP