简体   繁体   中英

How to split a string between digits and characters in java

I need to split a string that contains a series of numbers and characters. The numbers can have decimal place. It also has to take into account that the string can have or not have spaces. I need to figure out how to use the right regex.

I've tried different .split() configurations but it does not work the way I want it to work.

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"

The problem with the logic in your current lookarounds is that \\\\D matches any non digit character. This does include letters (such as kb ), but it also includes things like . , and any other non digit character. Try splitting between numbers and letters only:

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

This prints:

[123.45, 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