正则表达式中$ 1和$&之间的差异

ema*_*ren 8 javascript regex

我在$&使用正则表达式时偶然发现了.如果我使用,$1我会得到与之相同的结果$&.有什么特别之处$&,它在哪里记录

当我在duckduckgo或google上搜索"正则表达式+ $&"时,我找不到任何相关的匹配项.

在下面的示例中,可以使用$1$&.$&有什么特别之处,为什么它存在?

看看这个例子的小提琴

<div id="quotes">
  <ul>
    <li>???????!
      <ul>
        <li><b>Let's go!</b></li>
        <li>Variant translations: <b>Let's ride!</b></li>
        <li><b>Let's drive!</b></li>
        <li><b>Off we go!</b></li>
      </ul>
    </li>
  </ul>
  <ul>
    <li><i>??????? ????? ? ???????-????????, ? ??????, ??? ????????? ???? ???????. ????, ????? ??????? ? ??????????? ??? ???????, ? ?? ????????? ??!</i>
      <ul>
        <li><b>Orbiting Earth in the spaceship, I saw how beautiful our planet is. People, let us preserve and increase this beauty, not destroy it!</b></li>
      </ul>
    </li>
  </ul>
</div>

<script>
    var quotes = document.getElementById("quotes"),
        html   = quotes.innerHTML,
        match  = /(let)/gi;

    // $1 gives same result
    quotes.innerHTML = html.replace(match, "<mark>$&</mark>");
</script>
Run Code Online (Sandbox Code Playgroud)

T.J*_*der 8

$&是完整匹配(所有匹配文本)的“替换”(要替换的内容的占位符) 。$1是第一个捕获组的“替代”。

所以:

var str = "test".replace(/s(t)/, "$&$1");
Run Code Online (Sandbox Code Playgroud)

给我们

测试

因为$&st$1t


and*_*lrc 6

$&返回整个匹配的字符串,而$1, $2, ... 返回捕获的匹配项。

考虑以下:

'abc abc'.replace(/(a)(b)./g, '$1'); // a a
'abc abc'.replace(/(a)(b)./g, '$2'); // b b
'abc abc'.replace(/(a)(b)./g, '$&'); // abc abc
Run Code Online (Sandbox Code Playgroud)


Wik*_*żew 5

$&$1是不一样的.

您获得相同的值,因为您将整个模式包含在捕获组中.

$&是对整个匹配$1的反向引用,而是对捕获组1捕获的子匹配的反向引用.

参见MDN String#replace()参考:

$&               插入匹配的子字符串.
$n$nn  在哪里nnn是十进制数字,插入n第括号的子匹配串,所提供的第一个参数是一个RegExp对象.

有关替换反向引用的更多详细信息,请访问regular-expressions.info.