问题
I am trying to accept a capture group only if the pattern matches and there is not a specific word before the end of the group. I've tried a # of approaches and none seem to work, clearly I'm not getting the concept:
https://regex101.com/r/iP2xY0/3 https://regex101.com/r/iP2xY0/4
Regardless of what I do my capture group captures something and my goal is if the reject word exists in the middle of the pattern to return no match.
RC:\*.*?(?P<Capture>(Bob|David|Ted|Alice))(?!Reject).*
- RC:* Hi Bob Smith<\person>
- RC:* Hi David Jones *Notes Bla bla<\person>
- RC:* Hi Ted Warren *Rejected <\person>
Capture Namegrouop is supposed to return:
- Bob
- David
- ''
So "Reject" says if the NameGroup Capture is found followed by anything ending in <
capture it, if between the NameGroup and the < the word Reject
appears do not.
回答1:
I would recommend putting your negative look-ahead at the beginning of your pattern. This first checks if your reject word exists in your string and only if it isn't there does it try to match the rest of the string:
(?!.*Rejected.*)RC:\*.*?(?P<Capture>(Bob|David|Ted|Alice)).*
https://regex101.com/r/iP2xY0/6
来源:https://stackoverflow.com/questions/39482021/fixing-negative-assertion-for-end-of-string