Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a dot have to be escaped in a character class (square brackets) of a regular expression?

A dot . in a regular expression matches any single character. In order for regex to match a dot, the dot has to be escaped: \.

It has been pointed out to me that inside square brackets [] a dot does not have to be escaped. For example, the expression: [.]{3} would match ... string.

Doesn't it, really? And if so, is it true for all regex standards?

like image 959
Dariusz Avatar asked Nov 14 '13 11:11

Dariusz


People also ask

Do you need to escape dot in regex?

(dot) metacharacter, and can match any single character (letter, digit, whitespace, everything). You may notice that this actually overrides the matching of the period character, so in order to specifically match a period, you need to escape the dot by using a slash \. accordingly.

What characters must be escaped in regex?

Operators: * , + , ? , | Anchors: ^ , $ Others: . , \ In order to use a literal ^ at the start or a literal $ at the end of a regex, the character must be escaped.

How do you represent a dot in regex?

in regex is a metacharacter, it is used to match any character. To match a literal dot in a raw Python string ( r"" or r'' ), you need to escape it, so r"\." Unless the regular expression is stored inside a regular python string, in which case you need to use a double \ ( \\ ) instead.

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


1 Answers

In a character class (square brackets) any character except ^, -, ] or \ is a literal.

This website is a brilliant reference and has lots of info on the nuances of different regex flavours. http://www.regular-expressions.info/refcharclass.html

like image 59
lilactiger89 Avatar answered Oct 29 '22 08:10

lilactiger89