Skip to content

Instantly share code, notes, and snippets.

@LukeChannings
Last active October 26, 2017 16:14
Show Gist options
  • Save LukeChannings/706228926544d9fc622418738ae9c470 to your computer and use it in GitHub Desktop.
Save LukeChannings/706228926544d9fc622418738ae9c470 to your computer and use it in GitHub Desktop.
Tagged regular expressions
const tre = (strings, ...values) => {
const flags = values
.filter(v => v instanceof RegExp)
.map(re => re.flags)
.reduce(
(a, b) =>
a +
b
.split("")
.filter(char => !a.includes(char))
.join("")
)
return new RegExp(
String.raw(
strings,
...values.map(v => (v instanceof RegExp ? v.source : v))
),
flags
)
}
@LukeChannings
Copy link
Author

Usage

const a = /(?:\s+)?/
const b = /[A-Z0-9]/i
const c = /[^\s\u0022\u0027\u003e\u0025\u003d\u0000-\u001f\u007f-\u009f]+/u

const re = tre`(${a}|${b})?${c}`

In the example, re will equal /((?:\s+)?|[A-Za-z0-9])?[^\s\u0022\u0027\u003e\u0025\u003d\u0000-\u001f\u007f-\u009f]+/iu

It is also possible to use comments, like:

const re = tre`(${
a // non-capturing optional whitespace group
}|${
b // alphanumeric character class
})?${
c // you don't even want to know!
}`

Or

const re = tre`(${a /* foo */}|${b /* bar */)`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment