[英]Is it possible to use a quantifier on a non-capturing group ? - regex
我按正则表达式捕获了一个组,但我想捕获所有内容,但不捕获该组。 因此,组可以在String中的不同位置发生多次。
我的第一个想法是,以负向超前的方式解决它,但我以失败告终。 因此,我尝试与非捕获组一起使用,并且也卡在这里。
(bar)(baz)foo
我要foo。
这是我到目前为止的内容:
String input = "(bar) (baz) foo";
String matchesGroup = "((?=\\().*?\\))"; //matches (...)
// as Casimir et Hippolyte commented, I know use
// ((?:(...))+) for the non capturing group
String matchesFoo = "((?:"+ matchesGroup +")+)\\s(.*)";
Pattern pattern = Pattern.compile(matchesFoo);
Matcher matcher = pattern.matcher(input);
while (matcher.find()){
System.out.println(matcher.group());
}
但什么也没捕获
实际的:
预期:foo
我的正则表达式在哪里错?
由于您要匹配多个(...)组,请考虑可能的尾随空格,然后移动+
来量化其中的一个或多个(我将空格移动到该组中,而+
则将整个结构量化)
String matchesFoo = "(?:(?:(?=\\().*?\\))\\s?)+(.*)";
你为什么不试试这个:
String testtring = "matches matches foo";
testString = testString.replaceAll("matches", "");
System.out.println(testString);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.