我需要创建 java 模式来过滤数据,例如 13.6Gb、12MB、15.5Kb 我使用这些代码
Pattern p = Pattern.compile("(\\d+)(\\w+)");
Matcher m = p.matcher(content);
String num_letter = m.group(1);
String union = m.group(2);
但它不能检测十进制数,所以如何修改这个模式
我需要创建 java 模式来过滤数据,例如 13.6Gb、12MB、15.5Kb 我使用这些代码
Pattern p = Pattern.compile("(\\d+)(\\w+)");
Matcher m = p.matcher(content);
String num_letter = m.group(1);
String union = m.group(2);
但它不能检测十进制数,所以如何修改这个模式
尝试为小数部分添加条件匹配:
Pattern.compile("(\\d+(?:[.]\\d+)?)(\\w+)");
注意小数部分使用非捕获组。
Have 是条件小数匹配的一种变体:
Pattern.compile("(\\d+\\.?\\d+?)+(\\w+)");
如果您使用的是 eclipse,我更喜欢使用类似的工具:http: //myregexp.com/eclipsePlugin.html - 它让这一切变得简单。
盯着你的,我会说这样的(\\d+(\\.?(\\d+))?)
话,你可以先看看你有多少匹配组,然后再把你想要的匹配组拉出来。或者,使用命名的捕获组将更具可读性。
-瑞安