Java的正则表达式 “\\ d +”(仅限阿拉伯数字)不工作
问题描述:
输入字符串:07-000
Java的正则表达式 “\ d +”(仅限阿拉伯数字)不工作
JAVA正则表达式:\\d+
(仅限数字)
预期结果:07000
(仅输入字符串的数字)
那么为什么这个Java代码只返回07
?
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher("07-000");
String result = null;
if (matcher.find()) {
result = matcher.group();
}
System.out.println(result);
答
那么为什么这个Java代码只返回07?
它只返回07
,因为这是你的正则表达式中的第一组,你需要一个while循环让所有团体和以后你可以将它们连接起来,以获得所有数字在一个字符串。
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher("07-000");
StringBuilder sb = new StringBuilder();
while (matcher.find())
{
sb.append(matcher.group());
}
System.out.println("All the numbers are : " + sb.toString());
答
我猜你想要达到的目标是相当的:
Pattern pattern = Pattern.compile("\\d+");
Matcher matcher = pattern.matcher("07-000");
StringBuilder result = new StringBuilder();
// Iterate over all the matches
while (matcher.find()) {
// Append the new match to the current result
result.append(matcher.group());
}
System.out.println(result);
输出:
07000
事实上matcher.find()
将返回一个子序列在与匹配的输入所以如果你只调用它一次,你将只获得第一个子序列07
这里。所以,如果你想获得所有你需要循环的东西,直到它返回false
,表明没有更多可用的匹配。
但是,在这种特殊情况下,最好直接拨打myString.replaceAll("\\D+", "")
,用空的String
代替任何非数字字符。
为什么matcher.find只匹配数字的“一个”“集合”?那个文件在哪里?什么是“集合”? –
此文档位于:https://docs.oracle.com/javase/7/docs/api/java/util/regex/Matcher.html#find()。 'find'停在与模式匹配的最后一个字符处。 – Riaz
谢谢你Riaz和svasa,明白了。 –