看起来像一个简单的问题,我需要提取一个捕获组,并可选择使用定界字符串限制该组。
在下面的示例中,我提供了一个分隔字符串“cd”,并希望它在所有情况下都返回“ab”:“ab”、“abcd”和“abcdefg”
这是代码:
public static void main(String[] args) {
String expected = "ab"; // Could be more or less than two characters
String[] tests = {"ab", "abcd", "abcdefg"};
Pattern pattern = Pattern.compile("(.*)cd?.*");
for(String test : tests) {
Matcher match = pattern.matcher(test);
if(match.matches()) {
if(expected.equals(match.group(1)))
System.out.println("Capture Group for test: " + test + " - " + match.group(1));
else System.err.println("Expected " + expected + " but captured " + match.group(1));
} else System.err.println("No match for " + test);
}
}
输出是:
No match for ab
Capture Group for test: abcd - ab
Capture Group for test: abcdefg - ab
我认为前瞻可能会起作用,但我认为没有一个是可选的(即零个或多个实例)