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?

nhahtdh
  • 55,989
  • 15
  • 126
  • 162
user685275
  • 2,097
  • 8
  • 26
  • 32
  • BoltClock has answered your question, for more info on extracting numbers take a look at http://stackoverflow.com/questions/5917082/regular-expression-to-match-numbers-with-or-without-commas-and-decimals-in-text – entonio May 08 '11 at 23:51

1 Answers1

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));
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356