我的要求就是:把一个字符串中含有的代表数字的内容给输出,这个数字包括纯数字和带小数点的数字
例如下面的测试数字:
输入
增加0.78abc34
输出:
0.78
34
public static void test117() {
String regex = "(.*)[([1-9]\\d*\\.?\\d*)|(0\\.\\d*[1-9])](.*)";
// String data = "56.78";
String data = "增加0.78abc34";
String data1 = "abc34";
boolean result = Pattern.matches(regex, data);
boolean result2 = data1.matches(regex);
System.out.println(result);
System.out.println(result2);
Pattern pat = Pattern.compile(regex);
Matcher mat = pat.matcher(data);
while(mat.find()){
System.out.println(mat.group(1));
System.out.println(mat.groupCount());
}
}
------解决思路----------------------
用法不对,find方法是迭代方法,会影响到start和end指针的移动。
public static void test117() {
String regex = "\\d+(\\.?\\d+)";
Pattern pattern = Pattern.compile(regex);
// String data = "56.78";
String data0 = "增加0.78abc34";
String data1 = "abc12";
Matcher matcher0 = pattern.matcher(data0);
Matcher matcher1 = pattern.matcher(data1);
while(matcher0.find()){
System.out.println(data0.substring(matcher0.start(), matcher0.end()));
}
while(matcher1.find()){
System.out.println(data1.substring(matcher1.start(), matcher1.end()));
}
}
------解决思路----------------------
\\d+(\\.\\d+)?