2011-05-08 79 views
1

我有格式的字符串来提取一些“[232] .......”我想提取232出字符串的,我这样做的java:使用正则表达式中的字符串

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

,但它不工作,我有以下异常:

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

任何人都知道我怎么能解决这个问题,如果有一个更有效的方法,我做这种模式匹配在java中?

+0

BoltClock已经回答了你的问题,更多信息的提取数字看一看HTTP: //sackoverflow.com/questions/5917082/regular-expression-to-match-numbers-with-or-without-commas-and-decimals-in-text – entonio 2011-05-08 23:51:59

回答

6

group()没有任何参数返回整个匹配(相当于group(0))。这包括您在正则表达式中指定的方括号。

要提取的数量,通过1你的正则表达式中只返回第一个捕获组(([0-9]+)):

number = Integer.parseInt(matcher.group(1)); 
+0

它的工作原理,非常感谢 – user685275 2011-05-08 23:52:20