4 ms·
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 create
by pygy_ 8y ago
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=N4IgZglgNgpgziAXAbVAOwIYFsZJAOgAsAXLKEAGhAGMB7NYmBvEAXwvW10QICsEqdBk2J4hcYgAJgGAG60IAEwqTqGAA7EArgCcYKmBGKEYOlXrAq4MAI5am1fZLhawkAB6tJAXlW0s6rTWAEowAOYw7uoAOmixYFpo1MQQ9JJYGADWMAByXIoAwhraenAAFBBoihCOcACU0rGSkrBSED6SAIxNknolaJIJSSlpmDiFxbowZWNOkeoNwD3NEGCSFVU18EQYcADyAO5oAAo6tOqmxACeM1x1i8vNksZnB5JoMG8AojpnOmXREDRYFAkCSADU7y4EMkgOBgMkEDgkgwUD0GEUV0kWmsihRyIwqkmeihOEBdUerEelWqtWQswAuh12uDwY8+roBmpNFMyvMKQNJFS0MLYuIpNySjAAJKbWodYDsUkwCY8km+DLZPLjIpq+BlSVTWW0+ACsX0CSSABeploxygOI6LjcEHcZQA5AAqd0C8UotBY3wAemQwLgwIAygyg+a0JaMAGcvRQv0OkH8DG4kkLVIJDpKmEALIYYjUEw6J22exJaY9WaqqUAkB2WiMQEqEPuwHRuoUHo2s72nEAwXNOQKRRlCwG4kyuXbFuMe590eSQzGUwjp5Pax2BzTLvw90qBNXXuPMeJ5MwfqPAXNc+C6eGvTGrZwfCLmACs3ZuO0WB8CgWgwjKAADQEwFoWhD3hEB3QAIwwHRASQq0wPwDJS0IMo8wLYtsNMe5KBAaxYGSVI4zwAAmRAAAYAFoAGZOkQABWai2A4EBZjwfBqDgAQaHoRhmB4NgGSoKBKkyBAUE4HAxH8QJrAYvQIiiEjdHIHgSGIdQ4EQIMg0SdRMjCfj-CDOgAiCGA1PCeYAAE6PwAAWfBqOs5S7IcjT1HwfgSOuC48Dgah800CTWCAA https://flems.io/#0=N4IgZglgNgpgziAXAbVAOwIYFsZJAOgAsAXLKEAG...