-3

I have a code check if the user input is valid in the regular expression pattern. The patter is @ the problem is how to check if the character . appears consecutively

[a-z|A-Z|0-9|[.]{1}]+@[[a-z|A-Z|0-9]+ i've tried this patter so far.

    System.out.print("Enter your Email: ");
    String userInput = new Scanner(System.in).nextLine();

    Pattern pat = Pattern.compile("[a-z|A-Z|0-9|[.]{1}]+@[a-z|A-Z|0-9]+");
    Matcher mat = pat.matcher(userInput);

    if(mat.matches()){
        System.out.print("Valid");
    }else{
        System.out.print("Invalid");
    }

}

}

if the input is een..123@asd123 I expect the output will Invalid but if the input is een.123@asd123 the output will Valid

  • 1
    `[a-z|A-Z|0-9]` is wrong. You don't need the `|` in a character class. Change to `[a-zA-Z0-9]` – Andreas Apr 01 '19 at 16:46
  • `indexOf("..") == -1`. – luk2302 Apr 01 '19 at 16:58
  • `^(\w+\.?)+\w+@\w+$` if you want underscore, else just replace `\w` with `[a-zA-Z0-9]` – Aniket Sahrawat Apr 01 '19 at 17:02
  • Please reword your question. If you do not want consecutive .'s, use one of the very simple regexes provided. If you are validating an email address, this is probably a duplicate: https://stackoverflow.com/questions/201323/how-to-validate-an-email-address-using-a-regular-expression – TheWandererLee Apr 01 '19 at 17:12

2 Answers2

1

If you don't want consecutive periods, use [a-zA-Z0-9]+(?:\.[a-zA-Z0-9]+)*

Explanation

[a-zA-Z0-9]+      Match one or more letters or digits
(?:               Start non-capturing group
   \.               Match exactly one period
   [a-zA-Z0-9]+     Match one or more letters or digits
)*                End optional repeating group

With this pattern, the value cannot start or end with a period, and cannot have consecutive periods.


Alternatively, use a negative lookahead: (?!.*[.]{2})[a-zA-Z0-9.]+@[a-zA-Z0-9]+

Explanation

(?!.*[.]{2})                 Fail match if 2 consecutive periods are found
[a-zA-Z0-9.]+@[a-zA-Z0-9]+   Match normally
Andreas
  • 154,647
  • 11
  • 152
  • 247
1

A character class matches any of the listed characters. If you specify a pipe | that does not mean OR but it could then also match a |.

If you don't want to match consecutive dots, you could make use of a character class that does not contain a dot, and then use a quantifier to repeat a grouping structure that does start with a dot.

^[a-zA-Z0-9]+(?:\.[a-zA-Z0-9]+)*@[a-zA-Z0-9]+(?:\.[a-zA-Z0-9]+)*$

That will match

  • ^ Start of string
  • [a-zA-Z0-9]+ Match 1+ times any character that is listed in the charater class
  • (?:\.[a-zA-Z0-9]+)* Repeat 0+ times a group which starts with a dot and matches 1+ times what is listed in the character class to prevent consecutive dots.
  • @ Match @ char
  • [a-zA-Z0-9]+ Match again 1+ chars
  • (?:\.[a-zA-Z0-9]+)* Match again repeating group
  • $ End of string

Regex101 demo

The fourth bird
  • 154,723
  • 16
  • 55
  • 70