Build regular expressions with functions.
const anyGreeting = either('howdy', 'hi', 'hey')
const regex = combine(anyGreeting, optional(','), ' ', capture(/\w+/))
regex // => /(?:howdy|hi|hey)(?:,)? (\w+)/
'hey bub'.match(regex)[1] // => 'bub'
Functions return a regular expression without flags. If you want any flags, call the flags
function last.
Regular expression input
may be either a RegExp
or a string. If it is a string, regex characters will be escaped - anyNumber('a+')
will match any number of occurrences of a+
in a string (/a\+*/
).
const {
combine,
flags,
capture,
either,
anyNumber,
oneOrMore,
optional,
exactly,
atLeast,
between,
anyNumberNonGreedy,
oneOrMoreNonGreedy,
optionalNonGreedy,
exactlyNonGreedy,
atLeastNonGreedy,
betweenNonGreedy,
} = require('regex-fun')
combine(/sup/, 'd*g') // => /supd\*g/
either(/this/, /that/, 'other thing') // => /(?:this|that|other thing)/
capture(/\w+/, either('this', 'that')) // => /(\w+(?:this|that))/
flags('gm', /HOWDY/i) // => /HOWDY/gm
anyNumber('wat') // => /(?:wat)*/
oneOrMore('wat') // => /(?:wat)+/
optional('wat') // => /(?:wat)?/
exactly(2, 'wat') // => /(?:wat){2}/
atLeast(3, 'wat') // => /(?:wat){3,}/
between(4, 5, 'wat') // => /(?:wat){4,5}/
anyNumberNonGreedy('wat') // => /(?:wat)*?/
oneOrMoreNonGreedy('wat') // => /(?:wat)+?/
optionalNonGreedy('wat') // => /(?:wat)??/
exactlyNonGreedy(2, 'wat') // => /(?:wat){2}?/
atLeastNonGreedy(3, 'wat') // => /(?:wat){3,}?/
betweenNonGreedy(4, 5, 'wat') // => /(?:wat){4,5}?/
This example is from verse-reference-regex, which finds and parses Bible verse ranges like "Revelation 13:5-6":
const requireVerse = true
const number = /(\d+)/
const numberAndOptionalLetter = /(\d+)([a-z])?/
const colonVerse = combine(':', numberAndOptionalLetter)
const chapterAndVerse = combine(number, requireVerse ? colonVerse : optional(colonVerse))
const secondHalfOfRange = combine(
'-',
either(
/([a-z])/,
/(\d+)([a-z])/,
chapterAndVerse,
numberAndOptionalLetter
)
)
const range = combine(chapterAndVerse, optional(secondHalfOfRange))
const regexThatMatchesVerses = combine(
capture(either(...bookNames, ...abbreviations)),
' ',
range
)
If you see a function missing, open a pull request, otherwise I'll add new functions as I need them.