Without any particular order, other options to match such patterns are:
Method 1
With non-capturing groups:
^(?:dog(?:, |$))+(?:cat)?$
Or with capturing groups:
^(dog(?:, |$))+(cat)?$
Method 2
With lookarounds,
(?<=^|, )dog|cat(?=$|,)
With word boundaries,
(?<=^|, )\b(?:dog|cat)\b(?=$|,)
Method 3
If we would have had only one cat
and no dog
in the string, then
^(?:dog(?:, |$))*(?:cat)?$
would have been an option too.
Test
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegularExpression{
public static void main(String[] args){
final String regex = "^(?:dog(?:, |$))*(?:cat)?$";
final String string = "cat\n"
+ "dog, cat\n"
+ "dog, dog, cat\n"
+ "dog, dog, dog\n"
+ "dog, dog, dog, cat\n"
+ "dog, dog, dog, dog, cat\n"
+ "dog, dog, dog, dog, dog\n"
+ "dog, dog, dog, dog, dog, cat\n"
+ "dog, dog, dog, dog, dog, dog, dog, cat\n"
+ "dog, dog, dog, dog, dog, dog, dog, dog, dog\n";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);
while (matcher.find()) {
System.out.println("Full match: " + matcher.group(0));
for (int i = 1; i <= matcher.groupCount(); i++) {
System.out.println("Group " + i + ": " + matcher.group(i));
}
}
}
}
Output
Full match: cat
Full match: dog, cat
Full match: dog, dog, cat
Full match: dog, dog, dog
Full match: dog, dog, dog, cat
Full match: dog, dog, dog, dog, cat
Full match: dog, dog, dog, dog, dog
Full match: dog, dog, dog, dog, dog, cat
Full match: dog, dog, dog, dog, dog, dog, dog, cat
Full match: dog, dog, dog, dog, dog, dog, dog, dog, dog
If you wish to simplify/modify/explore the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.
RegEx Circuit
jex.im visualizes regular expressions:
dog, dog, cat, blah
. I want to capture only first dog and optional cat (there can be at most one cat). – Suspiration