1

I have a string of format "[232]......." I want to extract the 232 out of the string, I did this

public static int getNumber(String str) {
    Pattern pattern = Pattern.compile("\\[([0-9]+)\\]");
    Matcher matcher = pattern.matcher(str);
    int number = 0;
    while (matcher.find()) {
        number = Integer.parseInt(matcher.group());
    }
    return number;
}

but it doesn't work, I got the following exception:

Exception in thread "main" java.lang.NumberFormatException: For input string: "[232]"

Anyone knows how could I solve this problem, and if there is a more efficient way for me to do this kind of pattern matching in java?

1

1 Answer 1

6

group() without any parameters returns the entire match (equivalent to group(0)). That includes the square brackets that you've specified in your regex.

To extract the number, pass 1 to return only the first capture group within your regex (the ([0-9]+)):

number = Integer.parseInt(matcher.group(1));
Sign up to request clarification or add additional context in comments.

Comments

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.