修复字符串末尾的否定断言 [英] Fixing Negative Assertion for end of string

查看:144
本文介绍了修复字符串末尾的否定断言的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我仅在模式匹配且在组末尾之前没有特定单词的情况下才尝试接受捕获组.我尝试了几种方法,但似乎都没有用,显然我没有领会这个概念:

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:*嗨鲍勃·史密斯< \ person>
  • RC:*大卫·琼斯*请注意Bla bla< \ person>
  • RC:*泰德·沃伦*拒绝了< \ person>
  • Capture Namegrouop应该返回:

    Capture Namegrouop is supposed to return:

    • 鲍勃
    • David
    • ''

    因此,拒绝"表示是否找到了NameGroup Capture,然后在NameGroup和<之间找到了以<结尾的任何内容.单词Reject不会出现.

    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.

    推荐答案

    我建议您将否定的前瞻性放在模式的开头.这首先检查您的拒绝词是否存在于字符串中,只有在不存在的情况下,它才会尝试匹配其余字符串:

    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

    这篇关于修复字符串末尾的否定断言的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆