$ 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
Wheren
ornn
are decimal digits, inserts then
th parenthesized submatch string, provided the first argument was aRegExp
object.
有关 替换后向引用可以在regular-expressions.info 找到。
More details on replacement backreferences can be found at regular-expressions.info.