似乎是一个简单的问题,我需要提取一个捕获组并选择使用定界字符串来限制该组。
在下面的示例中,我提供了一个定界字符串'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
我以为先行可能有效,但我不认为有一项是可选的(即零个或多个实例)
最佳答案
尝试这个:
Pattern pattern = Pattern.compile("(.*?)(?:cd.*|$)");
.*?
是非贪婪的,正则表达式的其余部分要么匹配cd
,然后匹配任何内容,要么匹配字符串的结尾。关于java - 具有可选定界符的正则表达式捕获组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5494845/