Last active
April 9, 2018 21:48
-
-
Save miyaokamarina/ce1c374cb505ca3786c38afaa52661d9 to your computer and use it in GitHub Desktop.
Multi-line regexps in JS made easy
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
const regexp = (xs, ...ys) => (xs2, ...ys2) => | |
new RegExp( | |
String.raw(xs, ...ys).replace( | |
// Find additional escape sequences, | |
// spaces, line breaks, comments: | |
/\\[#\n ]|#.*$|[\n ]/gm, | |
// Remove spaces, line breaks, comments, | |
// unescape additional sequences: | |
x => (x[0] === '\\' ? x[1] : ''), | |
), | |
String.raw(xs2, ...ys2), | |
); |
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
const date = regexp`^ | |
(?<year> \d{4}) - # Year | |
(?<month> \d{2}) - # Month | |
(?<day> \d{2}) # Day | |
$``u`; // ← Flags. | |
const { year, month, day } = date.exec('2018-03-29').groups; | |
console.log(`${parseInt(month)}/${parseInt(day)}/${parseInt(year)}`); // 3/29/2018 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment