我正在编写一个程序,其中用户输入以下格式的字符串:
"What is the square of 10?"
我需要检查字符串
.contains("\\d+")
或.contains("[0-9]+")
,则无论输入什么,程序都无法在字符串中找到数字,但.matches("\\d+")
仅在只有数字时才起作用。我可以使用什么作为查找和提取的解决方案?
发布于 2013-09-03 19:56:37
我使用的解决方案如下所示:
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));
}
我确信这不是一个完美的解决方案,但它满足了我的需求。谢谢大家的帮助。:)
发布于 2013-09-03 19:19:02
尝尝这个
str.matches(".*\\d.*");
发布于 2013-09-03 19:38:23
如果你想从输入字符串中提取第一个数字,你可以这样做-
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。
对于"abc1000def",1000。
对于"555abc45",555。
对于"abc",将返回空字符串。
https://stackoverflow.com/questions/18590901
复制相似问题