Fixing Negative Assertion for end of string

China☆狼群 提交于 2019-12-12 02:20:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!