2

I have a regular expression to check a string as email format as below:

Pattern p = Pattern.compile("^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@ + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$");

the correct email format is xxx.xxx@xxx.com

but sometimes my users complain they can't send email from the application due to invalid email format.

When using Matcher m = p.matcher(email);, how can I find out which word/char does not match against the regular expression?

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
user2074703
  • 141
  • 1
  • 5

2 Answers2

0

use

string.replaceAll

like this :

class Test {
  public static void main(String[] args) {
    String str = "word <a href=\"word\">word</word>word word";
    str = str.replaceAll("word(?!([^<]+)?>)", "repl");
    System.out.println(str);
  }
}

Then the strings not replace are what you want

Abadis
  • 2,671
  • 5
  • 28
  • 42
  • Are you sure you're answering the right question? I fail to see a connection here. – Tim Pietzcker May 20 '13 at 07:14
  • put your pattern in first part of replace function and a word to the second part. change your check your pattern part by part and you will find your problem – Abadis May 20 '13 at 07:20
0

This is not directly possible.

A regex fails or succeeds, it can't succeed partially, and if it fails, the regex engine usually doesn't give you access to the precise point of failure.

The more prominent problem to me is the fact that you're relying on a regex to validate an email address. This is never going to work, due to the fact that email addresses can be very complex.

It would make more sense to do a very basic check, i. e. check for "^.+@.+", and then do a proper validation with a parser, and with a test mail sent to that address with a verification code. You'll need to do that anyway because not every valid address is actually pointing to an existing mailbox, of course.

Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561