如何在Java中的数字和字符之间分割字符串

时间:2019-07-02 01:22:02

标签: java

我需要分割一个包含一系列数字和字符的字符串。数字可以有小数位。还必须考虑到字符串可以有或没有空格。我需要弄清楚如何使用正确的正则表达式。

我尝试了不同的.split()配置,但是它不能按照我想要的方式工作。

static int getBytes (String text) {

    //the string is split into two parts the digit and the icon
    String[] parts = text.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)");
    double num = Double.parseDouble(parts[0]);
    String icon = parts[1];

    // checks if the user enters a valid input
    if(parts.length > 2 || icon.length() > 3) {
        System.err.println("error: enter the correct format");
        return -1;
    }

    return 0;
}
 if i have a string text = "123.45kb"; i expect = "123.45", "kb"
 or text = "242.24 mg"; i expect = "242.24", "mg"
 or text = "234    b" i expect = "234", "b"

1 个答案:

答案 0 :(得分:2)

当前环顾四周的逻辑问题是\\D匹配任何个非数字字符。这的确包含字母(例如kb),但也包含诸如.之类的东西以及任何其他非数字字符。尝试仅在数字和字母之间分割:

String text = "123.45 kb";
String[] parts = text.split("(?<=[A-Za-z])\\s*(?=\\d)|(?<=\\d)\\s*(?=[A-Za-z])");
System.out.println(Arrays.toString(parts));

此打印:

[123.45, kb]
相关问题