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

时间:2018-09-15 13:31:06

标签: java regex user-interface

我不知道我的代码有什么问题,我只想接受一个具有以下格式的手机号码: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!");
    }

3 个答案:

答案 0 :(得分:1)

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

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

否则,它们将被视为必须出现的字符。

答案 1 :(得分:1)

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

示例1:

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

示例2:

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

答案 2 :(得分: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));
    }