The Complex One
The Complex One

Reputation: 77

Regex group match all words to end of string line

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

Answers (4)

Andrew
Andrew

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

The fourth bird
The fourth bird

Reputation: 163352

You could try it like this:

\w+\sloves\s(?:\w+,\s*)*\w+

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 character
  • loves 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 characters

Upvotes: 2

Alexcei Shmakov
Alexcei Shmakov

Reputation: 2343

Try it

\w+\sloves\s(\w+,\s*|\w+)*

Upvotes: 0

Scott Weaver
Scott Weaver

Reputation: 7361

try this pattern:

(\w+)\sloves\s(\w+),\s?(\w+)

regex101 demo

Upvotes: 0

Related Questions