I want to set a pattern which will find a capture group limited by the first occurrence of the “boundary”. But now the last boundary is used.
E.g.:
String text = "this should match from A to the first B and not 2nd B, got that?";
Pattern ptrn = Pattern.compile("\\b(A.*B)\\b");
Matcher mtchr = ptrn.matcher(text);
while(mtchr.find()) {
String match = mtchr.group();
System.out.println("Match = <" + match + ">");
}
prints:
"Match = <A to the first B and not 2nd B>"
and I want it to print:
"Match = <A to the first B>"
What do I need to change within the pattern?
Make your
*non-greedy / reluctant using*?:By default, the pattern will behave greedily, and match as many characters as possible to satisfy the pattern, that is, up until the last B.
See Reluctant Quantifiers from the docs, and this tutorial.