No need to escape the "." in a field [...] in REGEX?

Asked

Viewed 98 times

8

I was looking at some regular expressions here on the network, and I noticed that in many, in the character field, the . was not escaped \.. Thus : [a-zA-Z0-9.].
He doesn’t need the character \ before, no?

2 answers

9


No, because it would make no sense to allow "any character" in square brackets. Consider the example given. If the dot inside the bracket was special, the expression:

[a-zA-Z0-9.]

would be equivalent to simply:

.

(i.e. both marry "any character")

Since there’s no point in using it that way, . inside the bracket is considered a point even, and therefore does not need to be "escaped".

  • So if I put one +, {, $ you won’t need the character \ before?

  • 3

    No. Inside the brackets, the only things you would need to escape are the [, ] and the \ (obvious) and in some circumstances the ^ (if it is the first character of the set but is not a negation) and the - (if it is between one character and another but it is not an interval). Example.

  • 1

    complementing, brackets need not be escaped in the class if they are the first elements (e. g. [][0-9]+) and hyphen need not escape if it is the last character of the class (example [a-z0-9-]+)

  • 2

    @Sanction Ruble (Ruby) complained about its first example, but regex101 (Javascript) and Python accepted it well. I think it varies with the implementation. When in doubt, I would continue to escape the clasps. The hyphen is ok in all cases, and also does not need to escape if it is the first, or if it is between two intervals (e.g., in [a-z-A-Z] the hyphen between z and A is a hyphen even).

0

Have different meanings . can be any character, already \. is understood as the dot character.
But you should notice the context of the expression, in this case it is concatenating the intervals of a-z,A-Z,0-9 and also accepts the dot character.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.