0

I'm trying to validate a e-mail string in Java but I'm getting trouble to validate when this string has two or more special chars toghether, which is not a valid e-mail.

My if that does this validation is the following:

if (email.matches("(._\'!#$%&*+-\\/=?{|}~`^_-)\\1+")) {
    return false;
}

Example for the output:

this_e-mail's_valid@domain.com - return true (CORRECT)

this_e-mail_isn''t_valid@domain.com - return true (WRONG)

Obviously there's something wrong with my regular expression.

But I looked all over the internet to find some answer but didn't succeeded.

I've just read that using the "\1+" before expression, it was supposed to do this validation, but apparently it doesn't.

Thanks in advance for the answers!

4

2 に答える 2

0

I am not at all sure about your requirement. Email validation should be more than just this.

However, if you want to detect whether a string has 2 special characters consecutively or not, you can use

!string.matches("^.*([._\'!#$%&*+\\\\/=?{|}~`\\^-])\\1.*$") // It will invalidate the case that 2 consecutive characters are the same. e.g. not__valid, but it will give OK for va+-lid
OR
!string.matches("^.*[._\'!#$%&*+\\\\/=?{|}~`\\^-]{2}.*$") // Any sequence of consecutive special characters will be invalidate. e.g. not_+valid

Note that I logically negate the result. I'm matching the string if it contains consecutive characters.

I have tested and rectify the error in earlier revision.

于 2012-06-01T01:51:12.150 に答える
0

Ok, so first your regexp is trying to detect some special characters. $ denotes the end of a line, while \$ denotes a dollar sign. Whenever you need a special character you need to escape it preceeding it with \ So, I believe you want to detect $, curly braces, pipes, asterisks, question marks and plus signs. Those are only a few of the many special characters that you will need to escape.

To detect a bunch of special characters that can occur zero or more times you need to use the [] and the * directives like this:

[#'&!?]*

This will match any number of # or ' or ! Or ?

It can get even cooler by using \W which means anything that is not a character you'd find in a word.

I hope this helps fix your problem. It sounds like you'd benefit from this link: http://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html

于 2012-06-01T01:59:18.443 に答える