Search code examples
javaregexemail-validation

java.util.regex.PatternSyntaxException: Illegal repetition near index 12


I am new to regEx. I need to validate email using java. I have created regEx for email validation by hardcoding the domain name. But the domain name should be dynamic. I have passed the domain name as a parameter. But I don't know how to pass parameter in regEx.

But I tried this code, then I got the error "java.util.regex.PatternSyntaxException: Illegal repetition near index 12". I have followed some answers but it doesn't help for me. From those answers I understood about repetition quantifier. Can you tell me what I am missing here and how to solve this issue?

public static boolean validateEmail(String email, String domainName) {
      pattern = Pattern.compile("^([\\w-\\.]+)@ {"+ domainName +"}" , Pattern.CASE_INSENSITIVE);
    matcher = pattern.matcher(email);
    return matcher.matches();
  }




Solution

  • { and } have meaning in regex, namely for specifying how often the character before it can repeat. E.g. a{5} matches aaaaa.

    If you want to use curly braces in regex, you should escape them like \\{ and \\}.

    But that's not what you need for passing this as a parameter — it will just be literal text at that point. If you want to only match that literal domain, you could do Pattern.compile("^([\\w-\\.]+)@" + domainName, Pattern.CASE_INSENSITIVE).