This is a kind of contrived example, but I'm trying to find a general principle here.
The specified phrases written in English using this list form:
I have a cat I have a cat and a dog I have a cat, a dog, and a guinea pig I have a cat, a dog, a guinea pig, and a snake
Is it possible to use a regular expression to get all the elements, no matter how many there are? Please note that items may contain multiple words.
Obviously, if I have only one, then I can use I have a (.+) , And if there are exactly two of them, I have a (.+) and a (.+) Works.
But things get complicated if I want to compare not only one example. If I want to extract list items from the first two examples, I would think that this would work: I have a (.*)(?: and a (.*))? And although this works with the first phrase, telling me that I have cat and null , for the second he tells me that I have cat and a dog and null . Things only get worse when I try to combine phrases in even more forms.
Is there a way to use regular expressions for this purpose? This seems pretty simple, and I donβt understand why my regular expression works, which matches lists of two elements, but one that matches 1- or 2-position lists doesn't.
java regex
codebreaker
source share