简体   繁体   中英

java: use regular expression to extract a number in a string

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?

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

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