Make Your Regex Clearer - part 3

Adding comments inside regex

Some modern regex processors and their regex flavors support free-spacing mode. This mode allows the programmer to write regular expressions which are much easier for people to read and understand.

free-spacing mode and whitespaces

The main property of the free-spacing mode is that whitespaces (spaces, tabs and line breaks - line feed and carriage return) inside the regular expression are not taken into account by the regular expression processor. If you want to match a space in the free-spacing mode you can use \ , [ ] or the more readable form \x20

For Example:

 a   b*   ( c | d )   
is equal to:
 ab*(c|d)

free-spacing mode and Comments

Another property of the free-spacing mode is embeding comments in the regular expression. The charecter # start a new comment which ends at the end of the line. In other words, The content between # and the next newline character is ignored by the regex processor. If you want to match # charcter, you can use \#.

For Example:

 a # This is a comment which run until the end of the line
 b # This is another comment
is equal to:
 ab

Although Javascript does not support free-spacing mode out of the box, we can use the library XRegExp which support this form. In the next part, we will use those properties of the free-spacing mode with the help of XRegExp to make our code more readable.