Java 如何检查字符串中的正整数并删除其间的空格
我使用下面的方法验证字符串是否包含所有整数,并使用“parsePhone”方法返回它。但该程序无法检查字符串格式(如“09213 2321”)之间是否有空格。并输出一个已删除空格的字符串。此外,有没有更好的方法将这两种方法结合在一起Java 如何检查字符串中的正整数并删除其间的空格,java,validation,Java,Validation,我使用下面的方法验证字符串是否包含所有整数,并使用“parsePhone”方法返回它。但该程序无法检查字符串格式(如“09213 2321”)之间是否有空格。并输出一个已删除空格的字符串。此外,有没有更好的方法将这两种方法结合在一起 public static String parsePhone(String phone) { if(phone==null) return null; String s = phone.trim(); if(s.matches("^[0-
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;
}
试试这个:
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;
}
您将希望使用Java并从中获取
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 "";
}
这将删除所有非数字的字符。如果要验证字符串是否为电话号码,即使它包含空格,则可以按照以下
正则表达式模式查找
模式是:[0-9]*[0-9]*
如果您有任何特定的标准,比如空格应该用来分隔std code
和number
,那么您可以通过这种方式提供模式
注意:图案中有空格。试试这个
String s = "09213 2321";
boolean matches = s.matches("\\d+\\s?\\d+");
if (matches) {
s = s.replaceAll("\\s", "");
}
您有要解析的手机的格式吗>?