我有一个正则表达式,确保用户名只包含a-z或A-Z或0-9中的字符,并且在3-15个字符之间。
我想为每个人单独使用正则表达式:
1)检查它是否在3-15个字符之间(任何符号任何字母;仅 重要的是不是字符)
2)必须包含来自a-z或A-Z或0-9或的字符。 _(点和 下划线)(没有空格/空格)
3)a-z或A-Z中的字符(可以包含空格/空格)
这很好用:
private static final String PASSWORD_PATTERN = "^[a-zA-Z0-9_-]{3,15}$";
etlogin_username.addValidator(new RegexpValidator("Regex wrong", USERNAME_PATTERN));
以下内容返回false:
1)USERNAME_PATTERN1为“dummyu!:)”
返回false2)REALNAME_PATTERN为“Davic Schummer”返回false
private static final String USERNAME_PATTERN1 = "^\\w{3,15}$";
private static final String USERNAME_PATTERN2 = "^[a-zA-Z0-9_-]{3,15}$";
private static final String REALNAME_PATTERN = "^[a-zA-Z]$";
etlogin_username.addValidator(new RegexpValidator("Must be between 3-15 characters", USERNAME_PATTERN1));
etlogin_username.addValidator(new RegexpValidator("Symbols not allowed", USERNAME_PATTERN2));
etlogin_realname.addValidator(new RegexpValidator("Only alphabets allowed", REALNAME_PATTERN));
注意:我知道如何使用String.length;但是我想要一个正则表达式,因为我可以把它传递给Validator
,它会处理很多其他事情
Edit1:添加了正则表达式验证器:
public class RegexpValidator extends METValidator {
private Pattern pattern;
public RegexpValidator(@NonNull String errorMessage, @NonNull String regex) {
super(errorMessage);
pattern = Pattern.compile(regex);
}
public RegexpValidator(@NonNull String errorMessage, @NonNull Pattern pattern) {
super(errorMessage);
this.pattern = pattern;
}
@Override
public boolean isValid(@NonNull CharSequence text, boolean isEmpty) {
return pattern.matcher(text).matches();
}
}
答案 0 :(得分:0)
试试这个
public class UsernameValidator{
private Pattern pattern;
private Matcher matcher;
private static final String USERNAME_PATTERN = "^[a-z0-9_-]{3,15}$";
public UsernameValidator(){
pattern = Pattern.compile(USERNAME_PATTERN);
}
/**
* Validate username with regular expression
* @param username username for validation
* @return true valid username, false invalid username
*/
public boolean validate(final String username){
matcher = pattern.matcher(username);
return matcher.matches();
}
}
答案 1 :(得分:0)
使用正则表达式:
private static final String PASSWORD_PATTERN = "^.{3,16}$";
private static final String USERNAME_PATTERN1 = "^.{3,16}$";
private static final String USERNAME_PATTERN2 = "^[a-zA-Z0-9._-]$";
private static final String REALNAME_PATTERN1 = "^.{3,36}$";
private static final String REALNAME_PATTERN2 = "^[\\p{L} .'-]+$";