ChatGPT解决这个技术问题 Extra ChatGPT

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?

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.
@BoltClock there are some: posix, posix extended, perl. See en.wikipedia.org/wiki/Regular_expression#Standards
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).
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?

M
MrWhite

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


It really depends on how the language handles it, but for most languages this is true.
- is also literal if it's the last value
And ^ is literal if it's not the first character
If $ looks like a variable, it also needs to be escaped. E.g.: [$.]
@kimbo Yes, - doesn't need to be escaped if it's the first or last character inside a character class.