我正在尝试获取括号中数字的第一个匹配项并期望得到 123,但是:
String str = "ABC 123-(456)-(789)";
String regex = ".*\\((\\d+)\\).*";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(str);
m.find();
System.out.println(m.group(1)); // "789"
请帮忙。
我找到了解决方法但没有匹配器:
String[] arr = str.split("[\\(\\)]");
for (String s : arr) {
if (s.matches("[-+]?\\d+")) {
return s;
}
}
最佳答案
你的正则表达式的问题是默认情况下 *
量词是 greedy ,这意味着它会尽可能多地匹配。由于您将它与 .*
一起使用,这意味着它将尝试匹配最多 any 个字符,因为这就是 .
所代表的(行分隔符除外) ).
所以你的正则表达式 .*\((\d+)\).*
将匹配
ABC 123-(456)-(789)
.* -^^^^^^^^^^^^^^
((\d+)\) ---------------^^^^^
.* -empty
要更改 *
的行为并使其成为 reluctant,请添加 ?
,例如 .*?
。
但在您的情况下,您似乎应该从正则表达式中删除 .*
,因为您实际上可能不想匹配他们描述的部分。所以试试
String regex = "\\((\\d+)\\)";
对于像 "ABC 123-(456)-(789)"
这样的字符串,您应该得到结果 456
- 因为它是与此正则表达式匹配的第一个结果。要移动到文本结果 789
,您需要再次使用 find
方法。
所以你的代码看起来像:
private static final Pattern p = Pattern.compile("\\((\\d+)\\)");
//we make Pattern static field since to avoid recompiling
//same pattern each time we call our method
static String myFind(String text){
Matcher m = p.matcher(text);
if (m.find()){
return m.group(1);
}else{
return null;//or empty string, or maybe throw exception
}
}
关于java - 在Java中获取第一组正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34439793/