0

我使用下面的方法来验证一个字符串是否包含所有整数,并使用“parsePhone”方法返回它。但是这样的程序无法检查字符串格式之间是否有空格,例如 "09213 2321"。并输出一个去掉空格的字符串。此外,有没有更好的方法将这两种方法合二为一!?

public static String parsePhone(String phone)
{
    if(phone==null) return null;
    String s = phone.trim();

    if(s.matches("^[0-9]+$"))
    {
        while(s.startsWith("0")&& s.length()>1)
        {
            s = s.substring(1);
        }
        if(s.length()>=3) return s;
    }
    return null;
}

public static boolean phoneValidation(String phone)
{
    if(phone == null) return false;
    String string = phone.trim();

    if(string.matches("^[0-9]+$"))
    {
        while(string.startsWith("0")&& string.length()>1)
        {
            string = string.substring(1);
        }
        if(string.length()>=3) return true;
    }
    return false;

}
4

4 回答 4

0

如果您想验证一个字符串是否是电话号码,即使它包含一个空格,那么您可以按照以下内容regular expression pattern进行查找。

模式是:[0-9]* [0-9]*

如果您有任何特定标准,例如应该使用空格来分隔std codenumber那么您可以通过这种方式提供模式。

注意:图案中有空格。

于 2013-05-15T10:40:53.403 回答
0

尝试这个

    String s = "09213 2321";
    boolean matches = s.matches("\\d+\\s?\\d+");
    if (matches) {
        s = s.replaceAll("\\s", "");
    }
于 2013-05-15T10:41:01.257 回答
0

尝试这个:

public static String parsePhone(String phone)
{
    if(phone==null) return null;
    String s = phone.trim().replaceAll("\\s","");

    //The replaceAll will remove whitespaces

    if(s.matches("^[0-9]+$"))
    {

        while(s.startsWith("0")&& s.length()>1)
        {
            s = s.substring(1);
        }

        if(s.length()>=3) return s;
    }

return null;

}

public static boolean phoneValidation(String phone)
{
    return parsePhone(phone) != null;
}
于 2013-05-15T10:36:56.983 回答
0

您将需要使用Java 中的PatternMatcher

public static boolean phoneValidation(String phone) {
    if (phone == null) return false;
    String string = phone.trim();
    Pattern p = Pattern.compile('\\d');
    Matcher m = p.matcher(string);
    String result = "";

    while (m.find()) {
      result += m.group(0);
    }

    if (result.length() >= 3)
      return true;

    return false;
}

这应该查看字符串,找到每个数字字符并将它们一一返回,以添加到结果中。然后,您可以检查您的电话号码长度。

如果您希望该函数返回一个字符串,则将最后的 if 替换为:

if (result.length() >= 3)
  return result;

return "";

事实上,更快的方法是:

public static String phoneValidation(String phone) {
    if (phone == null) return false;
    String result = phone.replaceAll("[^\\d]", "");

    if (result.length() >= 3)
      return result;

    return "";

}

这将删除每个不是数字的字符。

于 2013-05-15T10:37:38.650 回答