106

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?

A-Tech
1,2298 silver badges29 bronze badges
asked May 1, 2012 at 13:01

4 Answers 4

133

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

answered May 1, 2012 at 13:05
Sign up to request clarification or add additional context in comments.

Comments

85

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.

answered May 1, 2012 at 13:04

3 Comments

and the minus(-) needs to be escaped only if it's in the middle of the range?
If you'd like to match hyphen, add it immediately after opening square bracket, e.g. [-A-Z]. Otherwise hyphen specifies range. It works in your case probably only because you're not specifing range in regex, but I'd suggest you follow the reference, in case you'll be adding range later.
or immediately before the closing bracket, or you could escape it with a slash
53

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

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

answered Oct 7, 2013 at 9:27

1 Comment

This one saved me today. I couldn't figure out why the expression wouldn't work. Thanks
5

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

A-Tech
1,2298 silver badges29 bronze badges
answered May 1, 2012 at 13:05

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.