Escape dot in a regex range

JavascriptRegexReplace

Javascript Problem Overview


For some reason those two regex act the same way:

"43\\gf..--.65".replace(/[^\d.-]/g, "");​  // 43..--.65
"43\\gf..--.65".replace(/[^\d\.-]/g, "");​  // 43..--.65

Demo

In the first regex I don't escape the dot(.) while in the second regex I do(\.).

What are the differences and why they act the same?

Javascript Solutions


Solution 1 - Javascript

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

Solution 2 - Javascript

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.

Solution 3 - Javascript

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

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

Solution 4 - Javascript

On this web page, I see that:

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questiongdoron is supporting MonicaView Question on Stackoverflow
Solution 1 - JavascriptjbabeyView Answer on Stackoverflow
Solution 2 - JavascriptusobanView Answer on Stackoverflow
Solution 3 - JavascriptMMiroslavView Answer on Stackoverflow
Solution 4 - JavascriptRob IView Answer on Stackoverflow