Lucas_123456 Lucas_123456 - 12 days ago 6
Java Question

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.

Answer

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