Ignoring whitespace in Javascript regular expression patterns?

后端 未结 2 1103
無奈伤痛
無奈伤痛 2021-01-17 09:52

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

2条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-17 10:42

    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(""));
    

提交回复
热议问题