我需要一个正则表达式来分隔字符串的整数和双元素,如下例所示:
String input = "We have the number 10 and 10.3, and i want to split both";
String[] splitted = input.split(/*REGULAR EXPRESSION*/);
for(int i=0;i<splitted.length;i++)
System.out.println("[" + i + "]" + " -> \"" + splitted[i] + "\"");
输出将是:
有人能帮助我吗?我将不胜感激。
答案 0 :(得分:2)
您需要匹配这些块:
\D+|\d*\.?\d+
请参阅regex demo
<强>详情:
\D+
- 除数字|
- 或\d*\.?\d+
- 一个简单的整数或浮点数(可能会增强到[0-9]*[.]?[0-9]+(?:[eE][-+]?[0-9]+)?
,请参阅source)A Java demo:
String s = "We have the number 10 and 10.3, and i want to split both";
Pattern pattern = Pattern.compile("\\D+|\\d*\\.?\\d+");
Matcher matcher = pattern.matcher(s);
List<String> res = new ArrayList<>();
while (matcher.find()){
res.add(matcher.group(0));
}
System.out.println(res);