简体   繁体   English

正则表达式,用于分割字符串中的双整数和整数

[英]Regular Expression to split double and integer numbers in a string

i need a regular expression to separate integer and double elements of a string, like the example below: 我需要一个正则表达式来分隔字符串的整数和双元素,如下例所示:

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] + "\"");

And the output will be: 输出将是:

  • [0] -> "We have the number " [0] - >“我们有号码”
  • [1] -> "10" [1] - >“10”
  • [2] -> " and " [2] - >“和”
  • [3] -> "10.3" [3] - >“10.3”
  • [4] -> ", and i want to split both" [4] - >“,我想分开两个”

Can someone help me? 有人能帮我吗? I will be grateful. 我会很感激。

You need to match these chunks with: 您需要将这些块与以下内容匹配

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

See the regex demo 请参阅正则表达式演示

Details : 细节

  • \\D+ - 1 or more chars other than digits \\D+ - 除数字以外的1个或更多字符
  • | - or - 要么
  • \\d*\\.?\\d+ - a simple integer or float (might be enhanced to [0-9]*[.]?[0-9]+(?:[eE][-+]?[0-9]+)? , see source ) \\d*\\.?\\d+ - 一个简单的整数或浮点数(可能会增强到[0-9]*[.]?[0-9]+(?:[eE][-+]?[0-9]+)?来源

A Java demo : Java演示

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); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM