这似乎是一个简单的问题,我需要提取一个捕获组并有选择地使用定界字符串限制该组。
在下面的示例中,我提供了一个分隔字符串“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/