Usage
Quick Example
import { lineStart, oneOf } from 'readable-regexp';
const regExp = lineStart
.captureAs`filename`.oneOrMore.char
.exactly`.`
.captureAs`extension`(
oneOf`ts``js`
.maybe`x`
)
.lineEnd
.toRegExp();
console.log(regExp); // /^(?<filename>.+)\.(?<extension>(?:ts|js)x?)$/
regExp.test('readable-regexp.ts');Syntax Rules
readable-regexp has a super flexible syntax. Most of the rules listed here are optional shorthands for your convenience rather than strict requirements.
Chain function calls with
.to represent consecutive tokens.exactly`fo`.maybe`o`=foo?
Using a tagged template literal is equal to calling the function with one string argument. Interpolation also works in the tagged template literals.
exactly`foo`=exactly('foo')exactly`foo${someVar}`=exactly('foo' + someVar)
Chaining function calls is equal to calling the function with multiple arguments.
oneOf`foo` `bar` `baz`=oneOf('foo')('bar')('baz')=oneOf('foo', 'bar', 'baz')oneOf`foo` `bar` (maybe.digit)=oneOf('foo', 'bar', maybe.digit)
All expressions can be coerced to string. This is especially useful in character classes.
charIn`${word}-.`=charIn`\w-.`
If a function expects an expression and your expression consists of 1 token only, you can chain the call to omit the bracket.
oneOrMore(word)=oneOrMore.wordmaybe(not(digit))=maybe.not.digit
All group constructs accept string literals as well as expressions, and you can use tagged template literals to omit the bracket.
capture(exactly('foo'))=capture`foo`
All expressions are immutable. You can freely extract and reuse them.
const num = oneOrMore.digit;
const decimal = match(num).exactly`.`.match(num);
const integer = num.notAhead`.`; If you prefer, you may prefix all expressions with
r.to avoid having to import all functions separately.
import { r } from 'readable-regexp';
const regExp = r.oneOrMore(r.exactly`fo`.maybe`o`);import { oneOrMore, exactly } from 'readable-regexp';
const regExp = oneOrMore(exactly`fo`.maybe`o`);Last updated