Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Commenting Regular Expressions

I'm trying to comment regular expressions in JavaScript.

There seems to be many resources on how to remove comments from code using regex, but not actually how to comment regular expressions in JavaScript so they are easier to understand.

like image 299
plemarquand Avatar asked Mar 17 '13 16:03

plemarquand


People also ask

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string). Both are called anchors and ensure that the entire string is matched instead of just a substring.

What is \r and \n in regex?

\n. Matches a newline character. \r. Matches a carriage return character.

What does $1 do in regex?

The $ number language element includes the last substring matched by the number capturing group in the replacement string, where number is the index of the capturing group. For example, the replacement pattern $1 indicates that the matched substring is to be replaced by the first captured group.

What does curly braces mean in regex?

The curly brackets are used to match exactly n instances of the proceeding character or pattern. For example, "/x{2}/" matches "xx".


1 Answers

Unfortunately, JavaScript doesn't have a verbose mode for regular expression literals like some other langauges do. You may find this interesting, though.

In lieu of any external libraries, your best bet is just to use a normal string and comment that:

var r = new RegExp(
    '('      + //start capture
    '[0-9]+' + // match digit
    ')'        //end capture
); 
r.test('9'); //true
like image 197
Explosion Pills Avatar answered Sep 16 '22 20:09

Explosion Pills