我正在制作一个注册界面,其中包含:用户名、密码和确认密码。它必须检查用户名和密码的正则表达式。但无论我输入什么,它总是错的
用户名[1]使用JTextField 密码[1]和confirmPassInput使用JPasswordField
if ( nameLargeButton.equals("Sign-in")){
String user = username[1].getText();
char[] passChars = password[1].getPassword();
String pass = new String(passChars);
char[] cfPassChars = confirmPassInput.getPassword();
String cfPass = new String(cfPassChars);
//biểu thức chính quy
Pattern reUser = Pattern.compile("^[a-z0-9_-]{5,12}(?!\\\\s)$");
Pattern rePass = Pattern.compile("^.{6,}$");
if(e.getSource() == largeButton){
if (reUser.matcher(user).find() && rePass.matcher(pass).find() && pass.equals(cfPass)) {
JOptionPane.showMessageDialog(null, "Success", "Thông báo", JOptionPane.WARNING_MESSAGE);
}
else if (!reUser.matcher(user).find()){
JOptionPane.showMessageDialog(null, "Invalid Username", "Thông báo", JOptionPane.WARNING_MESSAGE);
resetLoginDialog();
}
else if (!rePass.matcher(pass).find()){
JOptionPane.showMessageDialog(null, "Invalid Password", "Thông báo", JOptionPane.WARNING_MESSAGE);
}
else {
// Mật khẩu không hợp lệ, hiển thị thông báo
JOptionPane.showMessageDialog(null, "Invalid", "Thông báo", JOptionPane.WARNING_MESSAGE);
}
}
}
我认为当我按下“登录”按钮时,它会将“用户名[1]”和“密码[1]”中的文本与“reUser”和“rePass”进行比较
username: Bababa
password: 123qwerty
confirm password: 123qwerty
上面的输入应该是正确的,但总是显示“无效的用户名” 我做错了什么?
根据此模式
^[a-z0-9_-]{5,12}(?!\\\\s)$
,您的用户名Bababa
不匹配,因为它包含大写字母。
模式匹配区分大小写。在您的模式中,您仅包含
a-z
,它们是小写字母。
要包含大写字母,您需要将
A-Z
添加到您的模式中。因此,将您的模式更改为 ^[a-zA-Z0-9_-]{5,12}(?!\\\\s)$
。