我需要一个正则表达式来分隔字符串的整数和 double 元素,如下例所示:
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] + "\"");
输出将是:
有人能帮我吗?我会很感激。
最佳答案
您需要将这些块与:
\D+|\d*\.?\d+
查看 regex demo
详细信息 :
\D+
- 1 个或多个除数字以外的字符 |
- 或 \d*\.?\d+
- 一个简单的整数或浮点数(可能会增强为 [0-9]*[.]?[0-9]+(?:[eE][-+]?[0-9]+)?
,请参阅 source ) 一个 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);
关于java - 正则表达式在字符串中拆分 double 和整数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/40758143/