TipsTips用户名合法判断
CAMELLIA用户名合法判断
在开发中经常设计用户名是否合法判断,判断的规则基本一致,采用正则进行判断。
示例代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| import java.util.regex.Pattern;
public class AccountValidation {
public static boolean isValidAccount(String account) { String regex = "^[a-zA-Z0-9_]+$";
Pattern pattern = Pattern.compile(regex);
return pattern.matcher(account).matches(); }
public static void main(String[] args) { String account1 = "user123"; String account2 = "user@123";
System.out.println(account1 + " is valid: " + isValidAccount(account1)); System.out.println(account2 + " is valid: " + isValidAccount(account2)); } }
|
封装为工具类:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| import java.util.regex.Pattern;
public class AccountValidation {
private static final String ACCOUNT_REGEX = "^[a-zA-Z0-9_]+$"; private static final Pattern pattern = Pattern.compile(ACCOUNT_REGEX);
public static boolean isValidAccount(String account) { return pattern.matcher(account).matches(); }
public static void main(String[] args) { String account1 = "user123"; String account2 = "user@123";
System.out.println(account1 + " is valid: " + isValidAccount(account1)); System.out.println(account2 + " is valid: " + isValidAccount(account2)); } }
|