简体   繁体   中英

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 "
  • [1] -> "10"
  • [2] -> " and "
  • [3] -> "10.3"
  • [4] -> ", and i want to split both"

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
  • | - or
  • \\d*\\.?\\d+ - a simple integer or float (might be enhanced to [0-9]*[.]?[0-9]+(?:[eE][-+]?[0-9]+)? , see 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); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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