2 * @fileoverview Rule to enforce requiring named capture groups in regular expression.
3 * @author Pig Fang <https://github.com/g-plane>
8 //------------------------------------------------------------------------------
10 //------------------------------------------------------------------------------
17 } = require("eslint-utils");
18 const regexpp = require("regexpp");
20 //------------------------------------------------------------------------------
22 //------------------------------------------------------------------------------
24 const parser = new regexpp.RegExpParser();
26 //------------------------------------------------------------------------------
28 //------------------------------------------------------------------------------
35 description: "enforce using named capture group in regular expression",
36 category: "Best Practices",
38 url: "https://eslint.org/docs/rules/prefer-named-capture-group"
44 required: "Capture group '{{group}}' should be converted to a named or non-capturing group."
51 * Function to check regular expression.
52 * @param {string} pattern The regular expression pattern to be check.
53 * @param {ASTNode} node AST node which contains regular expression.
54 * @param {boolean} uFlag Flag indicates whether unicode mode is enabled or not.
57 function checkRegex(pattern, node, uFlag) {
61 ast = parser.parsePattern(pattern, 0, pattern.length, uFlag);
64 // ignore regex syntax errors
68 regexpp.visitRegExpAST(ast, {
69 onCapturingGroupEnter(group) {
73 messageId: "required",
86 checkRegex(node.regex.pattern, node, node.regex.flags.includes("u"));
90 const scope = context.getScope();
91 const tracker = new ReferenceTracker(scope);
99 for (const { node } of tracker.iterateGlobalReferences(traceMap)) {
100 const regex = getStringIfConstant(node.arguments[0]);
101 const flags = getStringIfConstant(node.arguments[1]);
104 checkRegex(regex, node, flags && flags.includes("u"));