use*_*275 1 java regex matching
我有一串格式"[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;
}
Run Code Online (Sandbox Code Playgroud)
但它不起作用,我得到以下例外:
Exception in thread "main" java.lang.NumberFormatException: For input string: "[232]"
Run Code Online (Sandbox Code Playgroud)
任何人都知道如何解决这个问题,如果有一种更有效的方法让我在java中进行这种模式匹配?
group()没有任何参数返回整个匹配(相当于group(0)).这包括您在正则表达式中指定的方括号.
要提取数字,请传递1以仅返回正则表达式中的第一个捕获组(([0-9]+)):
number = Integer.parseInt(matcher.group(1));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10008 次 |
| 最近记录: |