正则表达式范围中的转义点

这两种 regex 的作用方式相同:

var str = "43gf\\..--.65";


console.log(str.replace(/[^\d.-]/g, ""));
console.log(str.replace(/[^\d\.-]/g, ""));

在第一个正则表达式中,我不转义点(.) ,而在第二个正则表达式中,我转义点(\.)。

有什么不同? 为什么结果是一样的?

147874 次浏览

Because the dot is inside character class (square brackets []).

Take a look at http://www.regular-expressions.info/reference.html, it says (under char class section):

Any character except ^-]\ add that character to the possible matches for the character class.

The dot operator . does not need to be escaped inside of a character class [].

On regular-expressions.info, it is stated:

Remember that the dot is not a metacharacter inside a character class, so we do not need to escape it with a backslash.

So I guess the escaping of it is unnecessary...

If you using JavaScript to test your Regex, try \\. instead of \..

It acts on the same way because JS remove first backslash.