【问题标题】:Emulating a negative lookbehind of unknown width in PCRE在 PCRE 中模拟未知宽度的负向回溯
【发布时间】:2017-10-12 11:54:03
【问题描述】:

我有following regex

(?<=:)\s*\w+

我只想从字符串中提取comp comp

savedPosition: comp;
CURLSCHET.NREC ('qwertyuiop'): noprotect;

当在所需模式之前的任何位置存在() 时,我想避免匹配noprotect 之类的情况。

【问题讨论】:

  • 只是为了明确一点:您有一个多行字符串,并且您想匹配不包含 () 的行上的特定单词?另外,你真的也想得到空匹配吗?我认为你需要\w+,而不是\w*
  • 如果该行是: noprotect; (word),是否要提取noprotect?对于整行不应包含 () 以及一行上的 word 之前不应有 () 的情况,解决方案将有所不同。
  • Wiktor Stribiżew,感谢您在第一条评论中的提示。是的,如果行是: noprotect; (word),我想提取noprotect
  • 这令人心碎,因为我实际上并不知道所有细节。试试(?m)(?:^|\G)[^()\n]*?:\h*\K\w+ - 这将在一行中的第一个() 之前获取多次出现的匹配项。
  • Wiktor Stribiżew,它似乎有效。谢谢!

标签: regex pcre


【解决方案1】:

PCRE 不支持未知宽度的负向后查看(.NET 支持,它会在那里看起来 like this),但您可以使用第一个 () \G\K 运算符的组合,在否定字符类 [^()] 的帮助下,将匹配除 () 之外的任何字符。

你可以使用

(?m)(?:^|\G)[^()\n]*?:\h*\K\w+

regex demo

详情

  • (?m) - 多行模式开启
  • (?:^|\G) - 匹配字符串/行的开头或前一个匹配的结尾
  • [^()\n]*? - 除() 和换行符之外的任何 0+ 个字符,尽可能少
  • : - 冒号
  • \h* - 0+ 个水平空格
  • \K - 匹配重置运算符,丢弃到目前为止匹配的所有文本
  • \w+ - 1 个或多个单词字符。

【讨论】:

    【解决方案2】:

    你应该试试这个:

    [^\(\):]*:\s*(\w*)
    

    解释:

    1. [^\(\):]*: 捕获所有没有 ( 和 ( 和 :
    2. : 后跟:
    3. \s* 后跟零个或多个空白字符
    4. \w* 后跟零个或多个长度的单词

    Demo

    替代方案:

    如果你不想匹配前面的部分,那么你也可以试试这个解决方案:

    ^(?=[^\(\):]*:).*:\s*\K(\w*)
    

    Alternative Demo

    【讨论】:

    • 您的第一个模式是个好主意,只是需要行锚的开始。 (?m)^[^():]*:\h*\K\w+
    【解决方案3】:

    : *\K\w+

    : matches the character : literally (case sensitive)
     *
    matches the character   literally (case sensitive)
    * Quantifier — Matches between zero and unlimited times, as many times as possible, giving back as needed (greedy)
    \K resets the starting point of the reported match. Any previously consumed characters are no longer included in the final match
    \w+
    matches any word character (equal to [a-zA-Z0-9_])
    + Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)
    

    【讨论】:

      猜你喜欢
      • 2016-02-04
      • 1970-01-01
      • 2018-03-22
      • 2018-06-23
      • 1970-01-01
      • 2015-07-12
      • 2015-08-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多