RegExp: Comments

I would love to have Perl compatible regular expression comments.

Comments begin with (?# and end at the next ).



need to prove this feature necessity

Personally I would like to see a built in way of composing RegExps. So variable names and existing JS comment syntax can be used to describe the pattern.

Something like:

let version = 4;
let variant = /[89aAbB]/; // 
let hex = /[a-f0-9]/;
let firstHalf = RegExp.from`${hex}{8}-${hex}{4}-${version}${hex}{3}`;
let secondHalf = RegExp.from`${variant}${hex}{3}-${hex}{12}`;
let uuids = RegExp.from`${firstHalf}-${secondHalf}`;

assert(uuids.source === /[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89aAbB][a-f0-9]{3}-[a-f0-9]{12}/.source);
RegExp.from = function ({ raw }, ...vars) {
  function varToString(v) {
    let isRegex = RegExp(v) === v;
    return isRegex ? v.source : String(v);

  return RegExp(
        .map((v, i) => (i === raw.length - 1 ? v : v + varToString(vars[i])))
1 Like

Regex can already feel so cluttered sometimes - maybe it needs something more than just comments. I personally love coffeescript's multiline regex, which allows for inline comments and it ignores whitespace. All of that together could really help to make a regex more readable.

Example from their website:

NUMBER     = ///
  ^ 0b[01]+    |              # binary
  ^ 0o[0-7]+   |              # octal
  ^ 0x[\da-f]+ |              # hex
  ^ \d*\.?\d+ (?:e[+-]?\d+)?  # decimal

(The # is the inline comment character in coffeescript).

I'd be okay with comments provided regexps spanning multiple lines is also permitted. Without it, I don't see how it's any more useful than a single-line comment above it explaining it.


I agree that being able to define a RegExp literal over multiple lines would be helpful but even without it a RegExp with multiple comments throughout it can be helpful so that you can insert logical breaks and say "the following is for X", etc.