1

I am new to regex. I am checking email ids using regex.

Following is my code to match <xyz@xyz.com> with xyz@xyz.com

Pattern p = Pattern.compile("\\<(.*?)\\>");
Matcher m = p.matcher("<xyz@xyz.com>");

And its working fine. Now I want to match either <xyz@xyz.com> or [xyz@xyz.com] with xyz@xyz.com.

Any suggestion will be appreciated.

Bhushan
  • 6,151
  • 13
  • 58
  • 91

4 Answers4

1
Pattern p = Pattern.compile("(<(.*?)>|\\[(.*?)])");
Steve Chambers
  • 37,270
  • 24
  • 156
  • 208
  • Thanks fo the answer I am getting his syntax Error when I try this code 'Invalid escape sequence (valid ones are \b \t \n \f \r \" \' \\ )' – Bhushan Sep 12 '13 at 12:44
  • Doh! Was in C# mode (where `@` before the string means you don't have to double-backslash). Just corrected by removing `@` and adding a backslash. – Steve Chambers Sep 12 '13 at 12:49
1
Pattern p = Pattern.compile("[\\[\\<](.*?)[\\]\\>]");
Matcher m = p.matcher("[xyz@xyz.com]");
System.out.println(m.matches());
Farlan
  • 1,860
  • 2
  • 28
  • 37
1

firstly < or > are not special characters for regex so you don't have to use \

your regex should be like this :

"(<|\\])(.*?)\\1" but this regex does't check email adress is valid or not if you want to control email is valid or not you will use this regex :

"(<|\\])([\\w\\-]([\\.\\w])+[\\w]+@([\\w\\-]+\\.)+[A-Z]{2,4})\\1"

but you should not use regex for email validation

Melih Altıntaş
  • 2,495
  • 1
  • 22
  • 35
  • Technically if a email address contains a `@` char and there is at least 1 char before and after the `@`, then its valid. Im not saying its an existing address just a possible valid address. http://tools.ietf.org/html/rfc2822#section-3.4.1 – string.Empty Sep 12 '13 at 13:22
1

Use

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

Reference http://www.mkyong.com/regular-expressions/how-to-validate-email-address-with-regular-expression/

Tarsem Singh
  • 14,139
  • 7
  • 51
  • 71