Reputation: 77
I have the following string format:
Mike loves Sarah, Wendy, Carmen, Jon
Wendy loves Josh, Polly, Sam
Barry loves 50cent,Obama,Donald, Mike
I want a regex expression to match on the pattern
person_name[space]loves[space]person_name[comma],person_name
person_name[space]loves[space]person_name[comma],[space]person_name
I have come up with the following expression. It matches well except for the last word
\w+\sloves\s(\w+,\s|\w+,)*
So in string
Mike loves Sarah, Wendy, Carmen, Jon
Wendy loves Josh, Polly, Sam
Jon and Sam won't be matched by my expression.
Please help
Thank you
Upvotes: 0
Views: 2457
Reputation: 315
Try:
\w+\sloves(\s?\w+,)*(\s?\w+)
There should be a better way to write this though. The "?" says that the previous character may or may not be present. So you would use it on the whitespace character if it may or may not be present. At first I thought using it on the comma would be a good idea, but thinking about it further it would probably trigger false positives like "Mike loves word word word, word" which is probably not what you want.
Upvotes: 0
Reputation: 163352
You could try it like this:
Capture one or more word character following by one or more white spaces \s*
in a non capturing group (?:
and repeat that zero or more times *
.
For the last word you could match one or more word characters \w
.
Explanation
\w+
Match one or more word characters\s
Match a whitespace characterloves
Match literally\s
Match a whitespace character(?:
Non capturing group
\w+,\s*
Match one or more whitespace characters followed by a comma and zero or more whitespace characters)*
Close non capturing group and repeat zero or more times\w+
Match one or more word charactersUpvotes: 2