ecma-262-regexp-parser v0.9.0
ECMA-262 regexp parser
Regexp Parser, implemented according to EMCA-262 Specification. Implemented all syntax constructions from es2022.
Requirements
Typescript >= 4.9
Node.js >= 16
Install
$ npm i ecma-262-regexp-parser --save
$ yarn global add ecma-262-regexp-parser
$ pnpm install --global ecma-262-regexp-parser
API Reference
parseRegexp(source: string | RegExp): RegexpNode
Returns AST of full regexp expression (e.g. /Hello!/gm
).
Throws, if got any syntax error.
import { parseRegexp } from 'ecma-262-regexp-parser';
const regexpNode = parseRegexp(/[A-z]*/gm);
parseRegexpNode(source: string): AnyRegexpNode
Returns AST of any regexp expression (e.g. (Hello|Hi)!
).
Throws, if got any syntax error.
import { parseRegexpNode } from 'ecma-262-regexp-parser';
const regexpNode = parseRegexpNode('(?:Maybe)\\snot');
printRegexpNode(node: AnyRegexpNode): string
Prints AST back to string as full representation (e.g. '/hello/gi'
)
import { printRegexpNode } from 'ecma-262-regexp-parser';
const regexp = parseRegexpNode(someAST);
createRegExpFromRegexpNode(node: RegexpNode): RegExp
Generates javascript RegExp
from RegexpNode
.
import { createRegExpFromRegexpNode, parseRegexp } from 'ecma-262-regexp-parser';
const regexpNode = parseRegexp(/a|b/);
const regexp = createRegExpFromRegexpNode(regexpNode);
console.log(regexp.test('a')) // <- true
traverseRegexpNode(node: RegexpNode, visitors: ...): void
Traverses nodes, can be used to collect information about regexp.
Visitors are object, where key is node name (or *
for calling on each node) and value is full visitor or shorthand:
import { traverseRegexp, parseRegexp } from 'ecma-262-regexp-parser';
const regexpNode = parseRegexp(/a|b/);
traverseRegexp(regexpNode, {
'*': (node) => console.log(node), // will log every node enter,
Group: {
enter(node) {
}, // will be called before child nodes traversing
exit(node) {
}, // will be called after all child nodes got traversed
},
})
factory
Exports all node creation methods. Names are matched node names, e.g. CharNode
-> factory.createCharNode
.
import { factory, CharType } from 'ecma-262-regexp-parser';
const charNode = factory.createCharNode('a', CharType.Simple, { start: 0, end: 0 });
types
Exports node type checkers, that can be used to narrow node type.
import { types, parseRegexpNode } from 'ecma-262-regexp-parser';
const node = parseRegexpNode('(a|b)');
if (types.isGroupNode(node)) {
// node type is narrowed to GroupNode
}
Enums
SyntaxKind
- describes all possible node types.ControlEscapeCharType
- types ofControlEscapeCharNode
;QuantifierType
- types ofQuantifierNode
;CharType
- types ofCharNode
.