开发者

What does \\$& in "str.replace(specials, "\\$&")" mean?

开发者 https://www.devze.com 2023-02-04 12:57 出处:网络
I am refering to code from Case insensitive string replacement in JavaScript?: RegExp.escape = function(str)

I am refering to code from Case insensitive string replacement in JavaScript?:

RegExp.escape = function(str) 
{
  var specials = new RegExp开发者_JAVA技巧("[.*+?|()\\[\\]{}\\\\]", "g"); // .*+?|()[]{}\
  return str.replace(specials, "\\$&");
}

What does \\$& mean?

I think \\ escapes the \ character. Then $&, I thought it should be $1 to match the 1st match? tho $1 does not work right


$& represents the entire (sub)string matched by the regex, regardless of capture groups. The replacement result you get is each match in your string being escaped by a literal backslash (represented by \\). Since the regex used here consists only of a character class, "each match" refers to each metacharacter listed in the character class that is matched.

For example, the regex string [abc] will be replaced with \[abc\]:

  • [ is matched as it occurs in the character class. Represented by $&, replaced with \[

  • a, b and c are not metacharacters in the character class, so they're ignored

  • ] is matched as it occurs in the character class. Represented by $&, replaced with \]


$& is the entire match, which in the example is whichever special character was matched. $1 doesn't work since there is no group (...) in the regex (though if you added parentheses around the square brackets, then it would also work).

Yes, the first '\' escapes the other (usually a backslash is used in conjunction with the following character to give it special meaning, so to get a literal backslash it needs to be escaped using another backslash).


That regex is not using a capture group. Apparently he is using a common regex variable:

$& returns the entire matched string (some systems its $0)
In this case he is just matching 1 character at a time equivalent to s/[.*+?|()\[\]{}\\]/\\$&/g

Obscure fact: In Perl there is a function called quotemeta("your string") that does this
or it can be inlined in the regex with \Q. I love Perl.

As a side note, he might have left out the carret ^ and possibly, but not sure, the $
The fact that there is no built-in or inline method might be a bad thing. And escaping metachars like this must be thought out, as regex fragments can be problematic.

0

精彩评论

暂无评论...
验证码 换一张
取 消