Java – Regular Expression Android

androidjavaregex

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){}

Best Answer

There are two problems with your current code:

  • The leading slash means it really is looking for "/@" rather than just "@". You seem to think that "/" does something special within a regex - it doesn't.
  • You're using matches() which tries to match the whole of the input; you want find which 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:

if (!valEmail.contains("@")) {
    ...
}

That will check whether the address contains any "@" signs. If you want to check that there's only one "@" sign, you could use:

int atIndex = valEmail.indexOf('@');
if (atIndex == -1) {
    // Handling for *no* @ sign
}
if (valEmail.indexOf('@', atIndex + 1) != -1) {
    // Handling for multiple @ signs
}

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:

// TODO: Compile this once and reuse
Pattern pattern = Pattern.compile("[^@]+@[^@]+");
Matcher matcher = pattern.matcher(valEmail);

if (!matcher.matches()) {
    ...
}

As an aside, this:

catch(Exception ex){}

is never a good idea. Please don't just ignore errors indiscriminately.