Those two regex act the same way:
var str = "43gf\\..--.65";
console.log(str.replace(/[^\d.-]/g, ""));
console.log(str.replace(/[^\d\.-]/g, ""));
In the first regex I don't escape the dot(.) while in the second regex I do(\.).
What are the differences? Why is the result the same?
4 Answers 4
The dot operator . does not need to be escaped inside of a character class [].
Comments
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.
3 Comments
-) needs to be escaped only if it's in the middle of the range?If you using JavaScript to test your Regex, try \\. instead of \..
It acts on the same way because JS remove first backslash.
1 Comment
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...