Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escape dot in a regex range

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?

like image 442
gdoron is supporting Monica Avatar asked May 01 '12 13:05

gdoron is supporting Monica


People also ask

Does DOT need to be escaped regex?

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

What does a dot do in regex?

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.

Is dot a special character in regex?

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

Is Dot a Escape character?

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.


1 Answers

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

like image 64
jbabey Avatar answered Oct 13 '22 06:10

jbabey