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

问题描述 投票:0回答:3

我不知道我的代码有什么问题,我想要的是接受这种格式的手机号码:09xxxxxxxxx(始终以“09”开头,总共11位数)。所有的努力将不胜感激。提前致谢。

Here is the picture of the problem

以下是代码:

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!");
    }
java regex user-interface
3个回答
1
投票

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

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

否则他们将被视为必须存在的角色。


1
投票

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

例1:

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

例2:

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

0
投票
    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));
    }
© www.soinside.com 2019 - 2024. All rights reserved.