检查并从 Java 中的 String 中提取一个数字

我正在编写一个程序,其中用户输入以下格式的字符串:

"What is the square of 10?"
  1. 我需要检查字符串中是否有数字
  2. 然后提取数字。
  3. 如果我使用 .contains("\\d+").contains("[0-9]+"),程序不能在字符串中找到一个数字,无论输入是什么,但是 .matches("\\d+")只有在只有数字时才能工作。

我可以使用什么作为查找和提取的解决方案?

434749 次浏览

尝试以下模式:

.matches("[a-zA-Z ]*\\d+.*")

试试这个

str.matches(".*\\d.*");
Pattern p = Pattern.compile("(([A-Z].*[0-9])");
Matcher m = p.matcher("TEST 123");
boolean b = m.find();
System.out.println(b);

你可以试试这个

String text = "ddd123.0114cc";
String numOnly = text.replaceAll("\\p{Alpha}","");
try {
double numVal = Double.valueOf(numOnly);
System.out.println(text +" contains numbers");
} catch (NumberFormatException e){
System.out.println(text+" not contains numbers");
}

因为您不仅要查找一个数字,而且还要提取它,所以您应该编写一个小函数来完成这项工作。一个字母一个字母地写,直到找到一个数字。啊,刚刚找到了堆栈溢出的必要代码: 在字符串中查找整数。看看公认的答案。

我认为它比正则表达式快。

public final boolean containsDigit(String s) {
boolean containsDigit = false;


if (s != null && !s.isEmpty()) {
for (char c : s.toCharArray()) {
if (containsDigit = Character.isDigit(c)) {
break;
}
}
}


return containsDigit;
}

如果想从输入字符串中提取第一个数字,可以这样做-

public static String extractNumber(final String str) {
    

if(str == null || str.isEmpty()) return "";
    

StringBuilder sb = new StringBuilder();
boolean found = false;
for(char c : str.toCharArray()){
if(Character.isDigit(c)){
sb.append(c);
found = true;
} else if(found){
// If we already found a digit before and this char is not a digit, stop looping
break;
}
}
    

return sb.toString();
}

例子:

对于输入“123abc”,上面的方法将返回123。

对于“ abc 1000def”,1000。

对于“555abc 45”,555。

对于“ abc”,将返回一个空字符串。

我提出的解决方案是这样的:

Pattern numberPat = Pattern.compile("\\d+");
Matcher matcher1 = numberPat.matcher(line);


Pattern stringPat = Pattern.compile("What is the square of", Pattern.CASE_INSENSITIVE);
Matcher matcher2 = stringPat.matcher(line);


if (matcher1.find() && matcher2.find())
{
int number = Integer.parseInt(matcher1.group());
pw.println(number + " squared = " + (number * number));
}

我知道这不是一个完美的解决方案,但它符合我的需要。谢谢你们的帮助。 :)

下面的代码对于“检查一个字符串是否包含 Java 中的数字”来说已经足够了

Pattern p = Pattern.compile("([0-9])");
Matcher m = p.matcher("Here is ur string");


if(m.find()){
System.out.println("Hello "+m.find());
}

s=s.replaceAll("[*a-zA-Z]", "")代替了所有的字母表

s=s.replaceAll("[*0-9]", "")代替所有数字

如果你做以上两个替换,你会得到所有特殊字符串

如果只想从 String s=s.replaceAll("[^0-9]", "")中提取整数

如果您只想从 String s=s.replaceAll("[^a-zA-Z]", "")中提取字母

快乐编码:)

public String hasNums(String str) {
char[] nums = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
char[] toChar = new char[str.length()];
for (int i = 0; i < str.length(); i++) {
toChar[i] = str.charAt(i);
for (int j = 0; j < nums.length; j++) {
if (toChar[i] == nums[j]) { return str; }
}
}
return "None";
}

.matches(".*\\d+.*")只适用于数字,而不适用于其他符号,如 //*等。

ASCII 位于 UNICODE 的开头,因此您可以执行以下操作:

(x >= 97 && x <= 122) || (x >= 65 && x <= 90) // 97 == 'a' and 65 = 'A'

我相信你能想出其他的价值观。

我找不到一个正确的模式。 请按照下面的指南,为一个小而甜的解决方案。

String regex = "(.)*(\\d)(.)*";
Pattern pattern = Pattern.compile(regex);
String msg = "What is the square of 10?";
boolean containsNumber = pattern.matcher(msg).matches();

下面的代码片段将告诉字符串是否包含数字

str.matches(".*\\d.*")
or
str.matches(.*[0-9].*)

比如说

String str = "abhinav123";


str.matches(".*\\d.*") or str.matches(.*[0-9].*)  will return true


str = "abhinav";


str.matches(".*\\d.*") or str.matches(.*[0-9].*)  will return false

当我在这里重定向寻找一种方法来找到字符串中的数字在 abc0语言,我将我的发现留在这里为其他人希望一个解决方案特定于 Kotlin。

查找字符串是否包含数字:

val hasDigits = sampleString.any { it.isDigit() }

查找字符串是否包含 只有数字:

val hasOnlyDigits = sampleString.all { it.isDigit() }

从字符串中提取数字:

val onlyNumberString = sampleString.filter { it.isDigit() }