如何使用正则表达式在java中验证电话号码

如何使用正则表达式在java中验证电话号码,java,regex,Java,Regex,电话号码应包含10位数字。如果超过10位,则应显示错误消息 String user = txtName.getText(); if(!user.matches("[a-zA-Z\\s]*")) { JOptionPane.showMessageDialog(null, "Invalid Name format !! \nPlease enter string only !!!"); } 来源信用证:嗨,看这里 这是一个如何使用正则表达式验证国际电话号码的示例。regex在这种情况下不是

电话号码应包含10位数字。如果超过10位,则应显示错误消息

String user = txtName.getText();
if(!user.matches("[a-zA-Z\\s]*")) {
    JOptionPane.showMessageDialog(null, "Invalid Name format !! \nPlease enter string only !!!");
}
来源信用证:

嗨,看这里


这是一个如何使用正则表达式验证国际电话号码的示例。

regex在这种情况下不是使用string user=txtName.getText()的最佳选择;如果(!user.matches(“[a-zA-Z\\s]*”){JOptionPane.showMessageDialog(null,“无效的名称格式!!\n请只输入字符串!!!”);}我已经用字符表示了,但我不知道电话号码。欢迎:)如果您觉得可以,请接受答案。附言:没关系,请先在谷歌上搜索一下,然后再问一下,这样可以节省别人的时间。
private static boolean validatePhoneNumber(String phoneNo) {
        //validate phone numbers of format "1234567890"
        if (phoneNo.matches("\\d{10}")) return true;
        //validating phone number with -, . or spaces
        else if(phoneNo.matches("\\d{3}[-\\.\\s]\\d{3}[-\\.\\s]\\d{4}")) return true;
        //validating phone number with extension length from 3 to 5
        else if(phoneNo.matches("\\d{3}-\\d{3}-\\d{4}\\s(x|(ext))\\d{3,5}")) return true;
        //validating phone number where area code is in braces ()
        else if(phoneNo.matches("\\(\\d{3}\\)-\\d{3}-\\d{4}")) return true;
        //return false if nothing matches the input
        else return false;

    }