単純な問題のように思えますが、キャプチャグループを抽出し、オプションで区切り文字列でグループを制限する必要があります。
以下の例では、「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
先読みは機能するかもしれないと思いましたが、オプションの先読み(つまり、0個以上のインスタンス)はないと思います。