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?
Special characters such as the dot character often need to be escaped in a regex pattern if you want to match them. For example, to match the actual dot '. ' character, you need to design a pattern with escaped dot '\.
In regular expressions, the dot or period is one of the most commonly used metacharacters. Unfortunately, it is also the most commonly misused metacharacter. The dot matches a single character, without caring what that character is. The only exception are line break characters.
If you want the dot or other characters with a special meaning in regexes to be a normal character, you have to escape it with a backslash. Since regexes in Java are normal Java strings, you need to escape the backslash itself, so you need two backslashes e.g. \\.
Yes that is true that DOT (and most other special characters) don't need to be escaped in character class. There is no "standard" for regular expression syntax. Worth noting that modern regex lets you escape any symbol even if not required, so you can just escape stuff when unsure.
The dot operator .
does not need to be escaped inside of a character class []
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With