1

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();
  }



Satheeshkumar
  • 75
  • 3
  • 12
  • You can use the solution from another question: https://stackoverflow.com/questions/40162591/how-to-validate-email-address-match-with-website-domain – Madina Saidova Nov 18 '19 at 13:11
  • Possible duplicate of [What is the best Java email address validation method?](https://stackoverflow.com/questions/624581/what-is-the-best-java-email-address-validation-method) – Didier L Nov 18 '19 at 13:16
  • Best is probably to first validate that you have a syntactically correct email address (which is hard to get right, especially using regex), then check that it ends with `@domainName`. – Didier L Nov 18 '19 at 13:18
  • @Didier L, I have validated by hardcoding the domain name like ```^([\\w-\\.]+)@(example.com | example.uk | example.co.in | example.edu.in )$. Since I am new to regEx, I don't know how to pass parameter in regEx. Now I learned and fixed. – Satheeshkumar Nov 18 '19 at 13:23
  • Thank you Didier L and @Madina Saidova for helping. – Satheeshkumar Nov 18 '19 at 13:24

1 Answers1

2

{ 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).

Nyubis
  • 528
  • 5
  • 12