正则表达式,用于分割字符串

时间:2016-11-23 07:11:21

标签: java regex split floating-point integer

我需要一个正则表达式来分隔字符串的整数和双元素,如下例所示:

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] - &gt; “我们有号码”
  • [1] - &gt; “10”
  • [2] - &gt; “和”
  • [3] - &gt; “10.3”
  • [4] - &gt; “,我想分开两个”

有人能帮助我吗?我将不胜感激。

1 个答案:

答案 0 :(得分:2)

您需要匹配这些块:

\D+|\d*\.?\d+

请参阅regex demo

<强>详情:

  • \D+ - 除数字
  • 以外的1个或多个字符
  • | - 或
  • \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);