Java: Parsing for empty spaces using Pattern and Matcher
I have a form with an edit box for entering valid email-address. I dont want the user to enter spaces in the email id edit box. As soon a text is entered i call two funcs
isEmailValid(String s) || isLoginValid(String s)
isEmailValid(String s){
Pattern pattern = Pattern.compile("^[\\.\\w-]*(@[\\.\\w-]*)?$");
Matcher matcher = pattern.matcher(string);
return matcher.matches();
}
开发者_开发技巧isLoginValid(String s){
Pattern pattern = Pattern.compile("^\\w+$");
Matcher matcher = pattern.matcher(string);
return matcher.matches();
}
This pattern works fine when the user enters the email-id for the first time. But as soon as the user deletes a char and enters a space, this logic breaks. I dont want user to enter spaces as email-id.
Can any help point out where i am going wrong?
I'm not 100% sure, but is it possible that it is matching the e-mails because it is matching your string because most everything is zero or more times? Followed by something that can happen zero or more times. Maybe try something like:
Pattern pattern = Pattern.compile("^[\\w]+[\\.\\w-]*(@[\\w-]+\\.[\\w-]+)?$");
I'm not sure if this will help. Also, You probably want both to have to be valid, but maybe not. It's worth considering if you wanted:
isEmailValid(String s) && isLoginValid(String s)
instead of:
isEmailValid(String s) || isLoginValid(String s)
but it's also possible (and potentially logical) that you meant what you wrote. Just a suggestion.
regexp are not universal matchers. the easiest way to solve your task is to make additional check for empty string:
if (org.apache.commons.lang.StringUtils.isBlank(email)) {
return false;
}
精彩评论