delta313 delta313 - 1 year ago 172
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


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.

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+") = " +;
}else {
System.out.println("Pattern does not match");

Answer Source

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



Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download