Faheem Kalsekar
Faheem Kalsekar

Reputation: 1420

Java Pattern Matching: Pattern.compile

I have an edit box. I am checking if the email address entered is valid or not.

Pattern pattern1 = Pattern.compile("^[\\w-]*@[\\.\\w-]*$");
Pattern pattern2 = Pattern.compile("^\\w+$");
Matcher matcher1 = pattern1.matcher(string);
Matcher matcher2 = pattern2.matcher(string);    
return matcher1.matches();
return matcher2.matches();

Problem with this if my input my email address as [email protected]. matcher return false. It consider the char "." as invalid.

How should i modify my code such that it supports "." and matcher return true.

Upvotes: 1

Views: 2946

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1502376

It's not clear why you've got two patterns (and two return statements!) instead of one... but your first pattern only includes \w and - before the @ sign, although it allows . afterwards. That's easy to modify, so that the first part is the same as the second part:

Pattern pattern1 = Pattern.compile("^[\\.\\w-]*@[\\.\\w-]*$");

However, there are plenty of sites giving rather more exact email address matching regular expression patterns - for example this one in Perl (which I suspect will port simply enough to Java). There's also a page with a fairly long explanation and Java code, if you want to also cope with addresses including friendly names. I'm sure if you search around you'll find a pattern which meets your exact needs - although quite how you judge which pages are reliable is another matter.

EDIT: If you want to be able to match without the last part, you can make it optional like this:

Pattern pattern1 = Pattern.compile("^[\\.\\w-]*(@[\\.\\w-]*)?$");

Upvotes: 4

Falmarri
Falmarri

Reputation: 48587

Pattern.compile("^[\\w-\.]*@[\\.\\w-]*$")

Note that this pattern will match non valid strings (assuming @ isn't a valid email address). And it will also not match other valid email addresses (ie [email protected])

Upvotes: 0

Related Questions