繁体   English   中英

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

[英]How to split a string between digits and characters in 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"

当前环顾四周的逻辑问题是\\\\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]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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