You may want to check out my lib, compose-regexp, which serves a similar purpose with a smaller API and weight (< 1KB mingzipped).
Named captures can be created with the following helper (with an example that parses strings):
import {avoid, capture, either, sequence, suffix} from 'compose-regexp'
function makeNamedCaptures(indices) {
let i = 1
return function namedCapture(name, exp) {
if (indices.hasOwnProperty(name)) {
throw new Error("\"" + name + "\" is already used as a capture name")
}
indices[name] = i ++
return capture(exp)
}
}
const captureIndices = {}, namedCapture = makeNamedCaptures(captureIndices)
const zeroPlus = suffix('*')
const any = /[\s\S]/
const anyNonReturn = /./
const stringMatcher = sequence(
namedCapture("quote", /['"]/),
zeroPlus(
avoid(ref(captureIndices.quote)),
either(
sequence('\\', any),
anyNonReturn
)
),
ref(captureIndices.quote)
)
// stringMatcher is actually a plain regexp:
console.log(`"foo'\\"'bar"baz`.match(stringMatcher))
// --> [ '"foo\'\\"\'bar"', '"', index: 0, input: '"foo\'\\"\'bar"baz' ]
You can off course parse strings without using back references, the goal here is to provide an example with a simple grammar that you can follow along.
For complex grammar with sub-parts, you can wrap the sb-patterns in functions and inject the `namedCapture` as a parameter.
https://flems.io/#0=N4IgZglgNgpgziAXAbVAOwIYFsZJAOgAsAXLKEAG...