java:使用正则表达式提取字符串中的数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5931168/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 13:30:06  来源:igfitidea点击:

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

javaregexmatching

提问by user685275

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

我有一个格式为“[232].......”的字符串我想从字符串中提取232,我这样做了

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?

任何人都知道我该如何解决这个问题,如果有更有效的方法可以在 Java 中进行这种模式匹配?

回答by BoltClock

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

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

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

要提取数字,传递1仅返回正则表达式中的第一个捕获组(([0-9]+)):

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