Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@DominoPivot
Last active August 19, 2022 16:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DominoPivot/9715bfb5a57fd0b6c4feefc353273b46 to your computer and use it in GitHub Desktop.
Save DominoPivot/9715bfb5a57fd0b6c4feefc353273b46 to your computer and use it in GitHub Desktop.
Parse regular expressions with comments and whitespace
// Tag which parses a multiline regexp pattern into a RegExp object, removing whitespace and comments
export function mrx (strings) {
if (strings.length !== 1) {
throw Error("mrx cannot process template strings with arguments.")
};
// capture pattern and flags from a string in format `/pattern/flags`
const captureRx = /^\s*\/(.*)\/([a-z]*)\s*$/si;
const match = captureRx.exec(strings.raw[0]);
if (match === null) {
throw Error("mrx could not parse regular expression pattern.");
}
// remove whitespace and comments from the pattern before bulding a regexp
const [, pattern, flags] = match;
const replaceRx = /\/\/[^\n]*|\s+/g;
return new RegExp(pattern.replace(replaceRx, ""), flags);
}

Multiline regex with comments

import { mrx } from "multiline-regular-expressions.js";

const measurementTokenRegex = mrx`
    / (\s+)                             // 1 whitespace
    | (\d+)\/(\d+)                      // 2,3 fraction
    | (\d*)([.,])(\d+)                  // 4,5,6 decimal
    | (\d+)                             // 7 integer
    | (km|cm|mm|m|ft|in|pi|po|'|")      // 8 unit
    /gi
`;

This is equivalent to:

const measurementTokenRegex = /(\s+)|(\d+)\/(\d+)|(\d*)([.,])(\d+)|(\d+)|(km|cm|mm|m|ft|in|pi|po|'|")/gi;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment