手机号码验证问题的正则表达式模式



我不知道我的代码出了什么问题,我只想接受这种格式的手机号码:09xxxxx所有努力将不胜感激。提前谢谢。

这是问题的图片

以下是代码:

String a2= jTextField6.getText();
String a3 = jTextField7.getText();
Pattern p = Pattern.compile("^(09) \d {9}$");
Matcher m = p.matcher(jTextField5.getText());
if (!m.matches()){         
int b = JOptionPane.ERROR_MESSAGE;
JOptionPane.showMessageDialog(this, "Invalid Mobile Number", "Error", b);    
return;
}
if (null==a2||a2.trim().isEmpty()){
int b = JOptionPane.ERROR_MESSAGE;
JOptionPane.showMessageDialog(this, "Fields should not left blank", "Error", b);
return;
} 
if(a3==null||a3.trim().isEmpty()){
int b = JOptionPane.ERROR_MESSAGE;
JOptionPane.showMessageDialog(this, "Fields should not left blank", "Error", b);  
}
else { 
int c = JOptionPane.YES_NO_OPTION;
int d = JOptionPane.showConfirmDialog(this, "Confirm Purchase?","Costume 1", c);
if (d==0){
JOptionPane.showMessageDialog( null,"Your costume will be delivered 3-5 working days." +"n"+"n"+"                   Thank You!");
}

您必须删除正则表达式中的空格:

Pattern p = Pattern.compile("^(09)\d{9}$");

否则,它们将被视为必须存在的字符。

使用注释模式忽略正则表达式模式中的空格。这可以通过在编译正则表达式模式时传递Pattern.COMMENTS标志或通过嵌入式标志表达式(?x)来完成。

示例 1:

Pattern p = Pattern.compile("^(09) \d {9}$", Pattern.COMMENTS);

示例 2:

Pattern p = Pattern.compile("(?x)^(09) \d {9}$");
final String regex = "^09\d{9}$";
final String string = "09518390956"; //matcb
//final String string = "11518390956"; // fails
//final String string = "09518390956 "; // fails
final Pattern pattern = Pattern.compile(regex);
final Matcher matcher = pattern.matcher(string);
while (matcher.find()) {
System.out.println("Full match: " + matcher.group(0));
}

最新更新