简体   繁体   中英

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

Expected output is 1.4 But output I want is, 1.4 kb

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
}

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