Reputation: 47
There's a few examples of the 'typical' solution to the problem, here in SO and elsewhere, but we need help with a slightly different version.
We have a string such as the following
pies
bob likes,
larry likes,
harry likes
cakes
And with the following regexp
(?<=pies\n|\G,\n)(\w+ likes)
Only when the string commences with pies we can capture the 'nnn likes' as expected, however, we'd also need that the capture fails if it doesn't end with 'cakes', and our attempts at doing so have failed.
Link to the regex101: https://regex101.com/r/uDNWXN/1/
Any help appreciated.
Upvotes: 2
Views: 1566
Reputation: 626738
I suggest adding an extra lookahead at the start, to make sure there is cakes
in the string:
(?s)(?<=\G(?!^),\n|pies\n(?=.*?cakes))(\w+ likes)
See the regex demo (no match as expected, add some char on the last line to have a match).
Pattern details
(?s)
- DOTALL/singleline modifier to let .
match any chars including line breaks(?<=
- a positive lookbehind that requires the following immediately to the left of the current location:
\G(?!^),\n
- right after the end of previous match, a comma and then a newline|
- or^pies\n(?=.*cakes)
- start of string, pies
, newline not followed with any 0+ chars as many as possible, and then a cakes
string)
- end of the lookbehind(\w+ likes)
- Group 1: any one or more letters, digits or underscores and then a space and likes
.Upvotes: 1