Repository: eslint/eslint
File: lib/rules/prefer-named-capture-group.js (JavaScript)

Code before:
        const sourceCode = context.getSourceCode();

        /**
         * Function to check regular expression.
         * @param {string} pattern The regular expression pattern to be check.
         * @param {ASTNode} node AST node which contains regular expression or a call/new expression.
         * @param {ASTNode} regexNode AST node which contains regular expression.
         * @param {boolean} uFlag Flag indicates whether unicode mode is enabled or not.
         * @returns {void}
         */
        function checkRegex(pattern, node, regexNode, uFlag) {
            let ast;

            try {
                ast = parser.parsePattern(pattern, 0, pattern.length, uFlag);
            } catch {

                // ignore regex syntax errors
                return;
            }

            regexpp.visitRegExpAST(ast, {
                onCapturingGroupEnter(group) {
                    if (!group.name) {
                        const rawText = sourceCode.getText(regexNode);
                        const start = regexNode.range[0] + rawText.indexOf("(", group.start) + 1;

                        context.report({
                            node,
                            messageId: "required",
                            data: {
                                group: group.raw
                            },
                            suggest: [
                                {
                                    fix(fixer) {
                                        return fixer.insertTextBeforeRange(
                                            [start, start],
                                            `?<temp${((pattern.match(/temp\d+/gu) || []).length || 0) + 1}>`
                                        );
                                    },
                                    messageId: "addGroupName"
                                },
                                {
                                    fix(fixer) {
                                        return fixer.insertTextBeforeRange(
                                            [start, start],
                                            "?:"
                                        );
                                    },
                                    messageId: "addNonCapture"

Review comment (suggestion):
This won't always find the correct `start`. For example:

```js
new RegExp("\u1234\u5678(?:a)(b)");
```

```
Capture group '(b)' should be converted to a named or non-capturing group.
```

"Add name to capture group" suggestion adds name to `(?:a)` instead of `(b)`:

```js
new RegExp("\u1234\u5678(?<temp1>?:a)(b)");
```

We could check if `regexNode` is a regex/string/template literal with raw text (the part that represents the pattern, e.g., source code text between quotes if it's a string literal) that is the same as `pattern`, and only in that case provide suggestions.

Code after:
        {
            fix(fixer) {
                const existingTemps = pattern.match(/temp\d+/gu) || [];
                const highestTempCount = existingTemps.reduce(
                    (previous, next) =>
                        Math.max(previous, Number(next.slice("temp".length))),
                    0
                );

                return fixer.insertTextBeforeRange(
                    [start, start],
                    `?<temp${highestTempCount + 1}>`
                );
            },
            messageId: "addGroupName"
        },
        {
            fix(fixer) {
                return fixer.insertTextBeforeRange(
                    [start, start],
                    "?:"
                );
            },
            messageId: "addNonCapture"
        }
    ];
}

//------------------------------------------------------------------------------
// Rule Definition
//------------------------------------------------------------------------------

/** @type {import('../shared/types').Rule} */
module.exports = {
    meta: {
        type: "suggestion",

        docs: {
            description: "Enforce using named capture group in regular expression",
            recommended: false,
            url: "https://eslint.org/docs/rules/prefer-named-capture-group"
        },

        hasSuggestions: true,

        schema: [],

        messages: {
            addGroupName: "Add name to capture group.",
            addNonCapture: "Convert group to non-capturing.",
            required: "Capture group '{{group}}' should be converted to a named or non-capturing group."