0

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"
1

1 Answer 1

2

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]
Sign up to request clarification or add additional context in comments.

2 Comments

try using replace to get rid of the spaces first - unless there is some need?
@stanleypena I updated my answer to handle this new edge case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.