readable-regex
A Node.js library for dynamically generating regular expressions in a readable fashion
Concept
Regular expressions, while incredibly powerful, are nasty to look at. The use all sorts of special characters and they are rarely constructed in code from smaller, named components. The idea of this library is to make it easier to read the components that go into a regular expression and to dynamically generate regular expressions using functions rather than string concatenation.
Example
const reg = const SOME_DIGITS = regconst DATE_CAPTURE = const match = regconsole //'Jan'
RegExp construction methods (more are planned)
It is not advisable to pass in regular expressions not generated by this library because they are all assumed to be concatenatable due to being previously wrapped in non-capturing groups.
reg(Array<string|RegExp>|string|RegExp[, Array<Flag>|Flag flags])
: constructs a new regular expression by concatenating the component(s). If there is only one component, it doesn't need to be wrapped in anArray
. Strings are interpreted as literal text and will be properly escaped (e.g.'\n[abc]'
will become/(?:\n\[abc\])/
). Flags are values of the objectreg.f
(global, case-insensitive, etc.).reg.times(RegExp, boolean notGreedy, number min[, number max])
: matches the regular expression at leastmin
times and at mostmax
times, if amax
is passed in. Making it not greedy will cause it to try to capture as few occurences as possible.reg.any(RegExp[, boolean notGreedy])
: matches 0 or more occurences of the regular expressionreg.some(RegExp[, boolean notGreedy])
: matches 1 or more occurences of the regular expressionreg.maybe(RegExp[, boolean notGreedy])
: matches 0 or 1 occurences of the regular expressionreg.thisMany(RegExp, number times)
: matchestimes
occurences of the regular expressionreg.capture(RegExp, string name)
: wraps the regular expression in a capturing group that can be referred to byname
reg.charIn(char|[char, char] ...chars)
: matches any of the specified characters. Individual characters specify a single character, whereasArray
s of 2 of them specify a range of characters.reg.charNotIn(char|[char, char] ...chars)
: matches any character besides the specified characters. Individual characters specify a single character, whereasArray
s of 2 of them specify a range of characters.reg.or(RegExp ...res)
: matches any instance of exactly one of the specified regular expressions
Functions
reg.exec(RegExp, string)
: likeRegExp.prototype.match(string)
except the returned match object, if notnull
, has aget
function which will take in the name of a capture group and return what was captured (see the example above)
Constants
reg.ANY
:.
reg.DIGIT
:\d
reg.START
:^
reg.END
:$
reg.ALPHANUM
:\w
reg.NOT_ALPHANUM
:\W
reg.WHITESPACE
:\s
reg.NOT_WHITESPACE
:\S
reg.WORD_BOUND
:\b
reg.IN_WORD
:\B
Flags
reg.f.GLOBAL
: theg
flagreg.f.IGNORE_CASE
: thei
flagreg.f.MULTILINE
: them
flagreg.f.UNICODE
: theu
flagreg.f.STICKY
: they
flag