I am trying to check if an at character only exist in an android edit-view. I am new to regular expression and i implemented the forthcoming code. where am i mistaken ? Here is my code
try {
Pattern pattern = Pattern.compile("/@");
Matcher matcher = pattern.matcher(valEmail);
if (!matcher.matches()) {
Toast.makeText(this," Invid no @ character ",Toast.LENGTH_LONG).show();
}
}catch(Exception ex){}
There are two problems with your current code:
matches()which tries to match the whole of the input; you wantfindwhich will just try to find a match for the regex somewhere in the input.Why are you using regular expressions at all though? Why not just:
That will check whether the address contains any “@” signs. If you want to check that there’s only one “@” sign, you could use:
If you do want to use regular expressions, there are rather more sophisticated email address validation regular expressions available. (There lots of different ones with different levels of validity – make sure you get one designed for the Java flavour of regex.) I wouldn’t use one just for this though – only use regular expressions where you’re really interested in pattern matching.
If you want to use a regex for “at least one non-@, following by @, followed by at least one non-@” you could use:
As an aside, this:
is never a good idea. Please don’t just ignore errors indiscriminately.