JavaScript 字符串替换中是否有子匹配组引用的 delimiter/disambiguation 语法?

Is there a delimiter/disambiguation syntax for submatch group references in JavaScript string replacement?

这一定已经有答案了,但我什至不知道要搜索什么。

在 JavaScript 中,我可以在替换字符串中引用带括号的子匹配,如下所示:

"abcdefghijklmnopqrstuvwxyz".replace(/(.)/g, "-");
// Result: "a-b-c-d-e-f-g-h-i-j-k-l-m-n-o-p-q-r-s-t-u-v-w-x-y-z-"

现在,我想在每个字母之间放置一个 1 而不是 -

"abcdefghijklmnopqrstuvwxyz".replace(/(.)/g, "");
// Result: "a1b1c1d1e1f1g1h1i1j1k1l1m1n1o1p1q1r1s1t1u1v1w1x1y1z1"

至少 Chromium 似乎检测到没有子匹配组 11,因此它将替换字符串解释为“子匹配组 1 后跟一个 1”。

我们假设有 11 个组:

'abcdefghijklmnopqrstuvwxyz'.replace(/^(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)$/, '');
// Result: "k"

我想知道的:

JavaScript 正则表达式引擎假定 $ 之后的最长数字序列是要引用的组 ID,前提是模式中存在这样的组,因此 1 将引用组如果模式中有一个,则为 111,如果有第 11 组,则为第 11 组和 1,如果少于 11 个组,则为第 1 组和 11。如果根本没有组(即 "x".replace(/./g, "") returns </code>),它将作为文字字符串返回。</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre><code>console.log('abcdefghijklmnopqrstuvwxyz'.replace(/^(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)$/, '')); // => "k" console.log('abcdefghijklmnopqrstuvwxyz'.replace(/^(.)(.)(.)(.)(.)(.)(.)(.)(.).................$/, '')); // => "a1"

如果您知道在您的模式中引用组可能有歧义,您可以用零填充组 ID

1 将被消歧为对第 1 组的反向引用和 1:

console.log('abcdefghijklmnopqrstuvwxyz'.replace(/^(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)$/, '1')); // => "a1"

不过,您也可以使用 named capturing groups with named backreferences:

console.log('abcdefghijklmnopqrstuvwxyz'.replace(/^(?<name>.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)(.)$/, '$<name>1')); // => "a1"

Table 54: Replacement Text Symbol Substitutions table 中,反向引用语法定义为 $n$nn,但是,甚至 $nnn 语法也是允许的。

Code units Unicode Characters Replacement text
0x0024, N Where 0x0031 ≤ N ≤ 0x0039 $n where n is one of 1 2 3 4 5 6 7 8 9 and $n is not followed by a decimal digit The nth element of captures, where n is a single digit in the range 1 to 9. If nm and the nth element of captures is undefined, use the empty String instead. If n > m, no replacement is done.
0x0024, N, N Where 0x0030 ≤ N ≤ 0x0039 $nn where n is one of 0 1 2 3 4 5 6 7 8 9 The nnth element of captures, where nn is a two-digit decimal number in the range 01 to 99. If nnm and the nnth element of captures is undefined, use the empty String instead. If nn is 00 or nn > m, no replacement is done.