Backslash in Regular Expression

3

I was studying java and the course instructor left me a challenge to validate an email using regular expressions.

I researched the regex API documentation ... part of the pattern .. The problem is that I found a code on the internet (which worked, of course) .. like this:

String regex = "[A-Za-z0-9\._-]+@[A-Za-z0-9]+(\.[A-Za-z]+)*";

In this case, I did not understand just why he put the characters "[" and "]," ("and") ", as well as the" \ "(which I know backslash, but I did not understand why it was used in this code.

Does anyone know?

    
asked by anonymous 29.01.2018 / 01:29

1 answer

3

[] : Used to match any character inside.

Example : [A-Z] matches the characters A through Z (note that only upper case)

() : Used to create a capturing group, to extract substrings, or to use as a reference.

Example : (.[A-Za-z]+)* will match the possible TLDs and * is a quantifier of 0 or more matches

The use of \ in the displayed expression was for the dot to be treated as the . character

If you would like to test your regular expressions quickly and learn more about using them, I suggest using RegExr

As noted by the Jefferson Quesado in the comment, using two \ instead of one is given to the fact that Java does not support "raw" strings, so \. is interpreted as \.

    
29.01.2018 / 01:55