3
was studying java and the course instructor left a challenge to validate an email using regular expressions.
I searched the regex API documentation...for the Pattern part.. The problem is that I found a code on the internet (which worked, obvious).. so:
String regex = "[A-Za-z0-9\\._-]+@[A-Za-z0-9]+(\\.[A-Za-z]+)*";
In this case, I didn’t understand just why he put the characters "[" and "]", "(" and ")" as well as the " " (which I know means the backslash, but I didn’t understand why it was used in this code.
Does anyone know?
Meaning of square brackets and of the Parentheses
– user28595
The backslash is the kryptonite of regular expression. But first there is the Java string interpretation, so to have a backslash in regex (to, say, neutralize the powers of
.
), in Java is written\\.
– Jefferson Quesado
The double backslash is to escape it. The list of the first part is limiting alphanumerics, including the dot, underline and hyphen, but point is also a regex character, then you need to escape it with a backslash. But java also recognizes the backslash as an escape, so you need to escape the java bar to then escape the point within the regular expression.
– user28595
Perfect! Thank you very much staff!
– João Victor Souza