Skip to content

Instantly share code, notes, and snippets.

@DmitrySoshnikov
Last active April 4, 2017 06:31
Show Gist options
  • Save DmitrySoshnikov/03d3ed23d35a1dd5ddfd8360afafb397 to your computer and use it in GitHub Desktop.
Save DmitrySoshnikov/03d3ed23d35a1dd5ddfd8360afafb397 to your computer and use it in GitHub Desktop.
regexp-tree-processing
const regexpTree = require('regexp-tree');
// Get AST.
const ast = regexpTree.parse('/[a-z]{1,}/');
// Handle nodes.
regexpTree.traverse(ast, {
// Handle "Quantifier" node type,
// transforming `{1,}` quantifier to `+`.
onQuantifier({node}) {
// {1,} -> +
if (
node.kind === 'Range' &&
node.from === 1 &&
!node.to
) {
node.kind = '+';
delete node.from;
}
},
});
// Generate the regexp.
const re = regexpTree.generate(ast);
console.log(re); // '/[a-z]+/'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment