Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignoring whitespace in Javascript regular expression patterns?

From my research it looks like Javascript's regular expressions don't have any built-in equivalent to Perl's /x modifier, or .NET's RegexOptions.IgnorePatternWhitespace modifier. These are very useful as they can make a complex regex much easier to read. Firstly, have I missed something and is there a Javascript built-in equivalent to these? Secondly, if there isn't, does anyone know of a good jQuery plugin that will implement this functionality? It's a shame to have to compress my complex regex into one line because of Javascript's apparent regex limitations.

like image 560
Jez Avatar asked Sep 30 '10 12:09

Jez


People also ask

How do you skip a space in regex?

You can stick optional whitespace characters \s* in between every other character in your regex.

Which modifier ignores white space in regex?

Turn on free-spacing mode to ignore whitespace between regex tokens and allow # comments, both inside and outside character classes.

What is the regex for white space?

The most common regex character to find whitespaces are \s and \s+ . The difference between these regex characters is that \s represents a single whitespace character while \s+ represents multiple whitespaces in a string.

What is \d in JavaScript regex?

The RegExp \D Metacharacter in JavaScript is used to search non digit characters i.e all the characters except digits. It is same as [^0-9]. Example 1: This example searches the non-digit characters in the whole string.


1 Answers

If I understand you correctly you want to add white space that isn't part of the regexp? As far as I know it isn't possible with literal regexp.

Example:

var a = /^[\d]+$/

You can break up the regexp in several lines like this:

var a = RegExp(
  "^" +
  "[\\d]+" +  // This is a comment
  "$" 
);

Notice that since it is now a normal string, you have to escape \ with \\

Or if you have a complex one:

var digit_8 = "[0-9]{8}";
var alpha_4 = "[A-Za-z]{4}";
var a = RegExp(
    digit_8 +
    alpha_4 + // Optional comment
    digit_8
 );

Update: Using a temporary array to concatenate the regular expression:

var digit_8 = "[0-9]{8}";
var alpha_4 = "[A-Za-z]{4}";
var a = RegExp([
    digit_8,
    alpha_4, // Optional comment
    digit_8,
    "[0-9A-F]" // Another comment to a string
 ].join(""));
like image 130
some Avatar answered Oct 01 '22 02:10

some