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 spunker.baba@foo.com. matcher return false. It consider the char “.” as invalid.
How should i modify my code such that it supports “.” and matcher return true.
It’s not clear why you’ve got two patterns (and two return statements!) instead of one… but your first pattern only includes
\wand-before the @ sign, although it allows.afterwards. That’s easy to modify, so that the first part is the same as the second part: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: