当我尝试在其他字母的字符串中匹配数字时,我遇到了麻烦,无法让@TheLostMind的答案起作用。最终我选择了以下方法:
\d+(,\d+)*(\.\d+)?
(需要转义这些反斜杠以在模式字符串中使用,即\\d+(,\\d+)*(\\.\\d+)?
)
注意:这并没有完全回答OP的问题,因为它没有直接检查是否有前导或尾随逗号,但如果数字确实有这个,它不会从CharSequence中提取它。
解释:
\d+
匹配一个或多个数字
(,\d+)*
匹配零个或多个“逗号后跟一个或多个数字”的组
(\.\d+)?
匹配零个或一个小数点后跟一个或多个数字的组
Pattern pattern = Pattern.compile("\\d+(,\\d+)*(\\.\\d+)?");
Matcher m1 = pattern.matcher("100,253,2586,3654");
Matcher m2 = pattern.matcher("100,253,2586,3654.999");
Matcher m3 = pattern.matcher("10,000,000,253,023,253,365,2536,2563,253");
Matcher m4 = pattern.matcher("10,000,456,258.99");
Matcher m5 = pattern.matcher("10.99");
Matcher m6 = pattern.matcher("1");
Matcher m7 = pattern.matcher("Text on the left 100,253,2586,3654.00000 text on the right");
Matcher m8 = pattern.matcher("Text on the left ,100,253,2586,3654.00000, text on the right");
System.out.println("Matcher 1 matches " + m1.find() + " result: " + m1.group());
System.out.println("Matcher 2 matches " + m2.find() + " result: " + m2.group());
System.out.println("Matcher 3 matches " + m3.find() + " result: " + m3.group());
System.out.println("Matcher 4 matches " + m4.find() + " result: " + m4.group());
System.out.println("Matcher 5 matches " + m5.find() + " result: " + m5.group());
System.out.println("Matcher 6 matches " + m6.find() + " result: " + m6.group());
System.out.println("Matcher 7 matches " + m7.find() + " result: " + m7.group());
System.out.println("Matcher 8 matches " + m8.find() + " result: " + m8.group());
输出:
Matcher 1 matches true result: 100,253,2586,3654
Matcher 2 matches true result: 100,253,2586,3654.999
Matcher 3 matches true result: 10,000,000,253,023,253,365,2536,2563,253
Matcher 4 matches true result: 10,000,456,258.99
Matcher 5 matches true result: 10.99
Matcher 6 matches true result: 1
Matcher 7 matches true result: 100,253,2586,3654.00000
Matcher 8 matches true result: 100,253,2586,3654.00000
\d+
- Tushar[\d,]+
与任何更复杂的答案一样正确。 - Dawood ibn Kareem