150

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?

Community
  • 1
  • 1
Dariusz
  • 21,561
  • 9
  • 74
  • 114
  • Yes that is true that DOT (and most other special characters) don't need to be escaped in character class. – anubhava Nov 14 '13 at 11:05
  • 5
    There is no "standard" for regular expression syntax. – BoltClock Nov 14 '13 at 11:06
  • 10
    @BoltClock there are some: posix, posix extended, perl. See http://en.wikipedia.org/wiki/Regular_expression#Standards – Dariusz Nov 14 '13 at 12:31
  • Worth noting that modern regex lets you escape any symbol even if not required, so you can just escape stuff when unsure. Only really need to worry about brevity when a super-concise one-liner is your goal, or your expression has too many slashes that it hurts readability. Over time you'll naturally learn how to write more cleanly. And sometimes it actually makes things easier to read when you consistently escape things like `(` or `?` so that at a glance you can see "this is a literal" without thinking about the context of where that token is (esp. with any crazy nesting). – Beejor Feb 10 '19 at 04:33
  • Suppose you were designing a regex engine and faced the question of whether a period within a character class must be escaped. The only reason for doing so would be to allow a non-escaped period in the character class to represent the meta-character `.`, which matches any character. But wait, what use is a character class that matches any character? – Cary Swoveland Mar 14 '20 at 02:05

1 Answers1

207

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

MrWhite
  • 43,179
  • 8
  • 60
  • 84
lilactiger89
  • 2,308
  • 1
  • 13
  • 14