delta313 delta313 - 3 months ago 17
Java Question

Regex Matching shortest match instead of longest

I am trying to write regex but having trouble making it work for some cases. Here is the regex

(\/[ABCGIKLNPRSUV])?(\/RC-[A-Z0-9]{2,6})?


The matches could be one of the following


  • /R/RC-ABC123

  • /R

  • /RC-ABC123



The above regex works for /R and /R/RC-ABC123 but not /RC-ABC123. For /RC-ABC123, it keeps matching against the first group instead of the second group and only takes /R as the matched component.

How can I make it work for all the cases. Also, the above expression is only a part of the full expression i.e. there could be another (third) group after RC-ABC123. But want to get it working for these 2 groups first.

Update
The ?? seems to work in regex101 but not in java. I get 2 groups but with null values for /R/RC-ABC123 using the following code

Pattern pattern = Pattern.compile("(/[A-Z])??(/RC-[A-Z0-9]{2,6})?");
Matcher matcher = pattern.matcher("/R/RC-ABC12345");
if(matcher.find()) {
for(int i=1; i<= matcher.groupCount(); i++) {
System.out.println("Group("+i+") = " + matcher.group(i));
}
}else {
System.out.println("Pattern does not match");
}

Answer

Make the first optional group non-greedy with ??, so it will prefer to match the second group if it has a choice.

(\/[ABCGIKLNPRSUV])??(\/RC-[A-Z0-9]{2,6})?

DEMO