Q:

Filtering String based on a format

I have a list of Strings and I want to filter them out based on either the pattern parta-partb-partc or parta-partb-no-partc. The no could be any positive integer while the other parts of the string are fixed.
For example

parta-partb-partc
parta-partb-1-partc
parta-partb-1xyz-partc
parta-partb-123-partc
parta-partb-abc-partc

After filtering by a regular expression my list should be
parta-partb-partc
parta-partb-1-partc
parta-partb-123-partc

My question is how do I write a regular expression combing both the conditions?

A:

Use String#matches with the following regex pattern:
parta-partb-(?:\d+-)?partc

Sample script:
String input = "parta-partb-1-partc";
if (input.matches("parta-partb-(?:\\d+-)?partc")) {
    System.out.println("MATCH");
}

Note that String#matches by default will apply the pattern to the entire input string, so no starting/ending anchors are required.

