$ 1和$&之间的差异在正则表达式中 [英] Difference between $1 and $& in regular expressions

查看:71
本文介绍了$ 1和$&之间的差异在正则表达式中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have stumbled upon $& when I use regular expressions. If I use $1 I get the same result as with $&. What is special with $&, and where is it documented?

我搜索正则表达式+ $&在duckduckgo或google上我找不到任何相关的匹配。

When I search for "regular expression +$&" on duckduckgo or google I can't find any relevant matches.

在下面的示例中,可以使用 $ 1 $& 。有什么关于$&和它为什么存在?

In the example below it is possible to use $1 or $&. What is special about $&, and why does it exist?

参见小提琴中使用示例

<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>


推荐答案

$& $ 1 不一样。

你得到相同的价值,因为你附上了捕获组中的整个模式。

You get the same value because you enclosed the whole pattern in a capturing group.

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

The $& is a backreference to the whole match, while $1 is a backreference to the submatch captured with capturing group 1.

请参阅MDN String#replace() reference

See MDN String#replace() reference:


$&                 插入匹配的子字符串。

$ n $ nn   其中 n nn 是十进制数字,插入 n 括号内的子匹配字符串,前提是第一个参数是 RegExp object。

$&               Inserts the matched substring.
$n or $nn  Where n or nn are decimal digits, inserts the nth parenthesized submatch string, provided the first argument was a RegExp object.

有关 替换后向引用可以在regular-expressions.info 找到。

More details on replacement backreferences can be found at regular-expressions.info.

这篇关于$ 1和$&amp;之间的差异在正则表达式中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆