Skip to content
Advertisement

Split strings in Java using RegEx

I want to split String a = "1.48 kb"; in java.

String a = "1.48 kb";
String[] fileNameSplit = a.split(".\s*[a-zA-Z]+");
System.out.println(fileNameSplit[0]);

Output is 1.4
But I want output: 1.4 kb

Advertisement

Answer

You can try using this:

Pattern pattern = Pattern.compile("^(\d+.?\d?)(\d*)(\s*[a-zA-Z]*)$");
Matcher matcher = pattern.matcher("1.48 kb");
if (matcher.matches()) { // true
   System.out.println(matcher.group(1)); // 1.4
   System.out.println(matcher.group(3)); //  kb

   String result = MessageFormat.format("{0}{1}", matcher.group(1), matcher.group(3));
   System.out.println(result); // 1.4 kb
}

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement