Last active
May 21, 2024 12:36
-
-
Save bholloway/c9d3bca2265e49e19cd8d1d04e91ecf4 to your computer and use it in GitHub Desktop.
Template literal for multiline regex with comments
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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
Support for flags:
=>
/import[s]+(?:([w$]+)[s]*)?(?:,[s]*)?(?:{([^}]*)}[s]*)?from[s]+'[^']+\/\/c\/my\/test\/file\.js(?:.js)?'/gim