Skip to content

Instantly share code, notes, and snippets.

@bholloway
Last active October 18, 2019 04:37
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bholloway/c9d3bca2265e49e19cd8d1d04e91ecf4 to your computer and use it in GitHub Desktop.
Save bholloway/c9d3bca2265e49e19cd8d1d04e91ecf4 to your computer and use it in GitHub Desktop.
Template literal for multiline regex with comments
/**
* Simple custom template literal that removes comments and whitespace in regex
*/
const regex = ({ raw }, ...substitutions) =>
new RegExp(
String.raw(
{ raw: raw.map(v => v.replace(/\s+#.*$/gm, '').replace(/[\s\r\n]+/g, '')) },
...substitutions,
),
);
/**
* Example: detect import syntax in text
*/
const detectImport = filename =>
regex`
import
[\s\r\n]+ # whitespace (possibly newline)
(?: # optional uncaptured
([\w$]+) # capture $1: default import
[\s\r\n]* # optional whitespace (possibly newline)
)?
(?: # optional uncaptured
,
[\s\r\n]* # optional whitespace (possibly newline)
)?
(?: # optional uncaptured
{
([^}]*) # capture $2: named imports text (anything but closing brace)
}
[\s\r\n]* # optional whitespace (possibly newline)
)?
from
[\s\r\n]+ # whitespace (possibly newline)
'[^']+/${filename}(?:\.js)?' # single quoted module specifier ending in given filename
`,
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment