So regular expressions seem to match on the longest possible match. For instance:
public static void main(String[] args) {
String s = "ClarkRalphKentGuyGreenGardnerClarkSupermanKent";
Pattern p = Pattern.compile("Clark.*Kent", Pattern.CASE_INSENSITIVE);
Matcher myMatcher = p.matcher(s);
int i = 1;
while (myMatcher.find()) {
System.out.println(i++ + ". " + myMatcher.group());
}
}
generates output
I would like this output
I have been trying Patterns like:
Pattern p = Pattern.compile("Clark[^((Kent)*)]Kent", Pattern.CASE_INSENSITIVE);
that don't work, but you see what I'm trying to say. I want the string from Clark to Kent that doesn't contain any occurrences of Kent.
This string:
ClarkRalphKentGuyGreenGardnerBruceBatmanKent
should generate output
greedy vs reluctant is your friend here.
try: Clark.+?Kent
You want a "reluctant" rather than a "greedy" quantifier. Simply putting a ? after your * should do the trick.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With