1

I am trying to validate email in java. Below is the code:

String mail = "[email protected]"; String regex = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$"; if(mail.matches(regex)){ System.out.println("valid email"); }; 

Now i want to restrict the length of Text1 and Text2 to 10 characters and length of Text3 to 5 characters.

I tried with this regex but did not work - ^[_A-Za-z0-9-]+(\.[_A-Za-z0-9-]{2,}+)*@[A-Za-z0-9]+(\.[A-Za-z0-9]+)*(\.[A-Za-z]{2,})$

How do i achieve this? Thanks.

3
  • It would be good to have examples of email addressed that are correct and ones that should be incorrect according to your requirement. Commented Jun 16, 2016 at 8:16
  • Also, please show on those emails, which part you consider text1/text2/text3. Commented Jun 16, 2016 at 8:16
  • 1
    You shouldn't do this. Go with something like .+@.+ or .+@.+\..+. Different providers allow different characters in email address. According to email address specification, you can actually put any character in there given that you escape it. Gmail for example allows the plus sign before @, for which I don't see handling in your regex. Also, gmail actually allows a dot as the first character which is invalid according to email address specification. Commented Jun 16, 2016 at 9:12

2 Answers 2

1

Here's the regex:

String regex = "^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]{0,10})*@[A-Za-z0-9]+(\\.[A-Za-z0-9]{0,10})*(\\.[A-Za-z]{0,5})$"; 

This doesn't count dots as a character, uses {n, m} syntax, it limits the number of characters to be between n and m occurrences.

Sign up to request clarification or add additional context in comments.

Comments

0

^[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9-]+)*(\\.[A-Za-z]{2,})$ I have used this another approach.

Comments