【问题标题】:Why this (?=^\s*)print_debug positive lookahead is not matching the \s* spaces?为什么这个 (?=^\s*)print_debug positive lookahead 与 \s* 空格不匹配?
【发布时间】:2016-11-25 23:43:49
【问题描述】:

为什么这个(?=^\s*)print_debug 正向预测与\s* 空格不匹配?

完整的正则表达式模式是(?=^\s*)print_debug。样本匹配为:

print_debug('scroll set: '+str(position));
print_debug('scroll set: '+str(position));
                print_debug('scroll set: '+str(position));
                print_debug('supposed current scroll: '+str(view.viewport_position())); # THIS LIES
            else:
                print_debug('SKIPPED...')

但它只匹配前两行:

这是一个在线正则表达式引擎的链接:

  1. https://regex101.com/r/RIIqTg/1

为什么\s*^ 一起使用时会被忽略?

  1. 如果删除^\s* 开始匹配。
  2. 如果添加^\s* 将停止工作。

我希望它在Sublime Text 上使用并禁用我的Python Sublime Text 包源代码文件中的所有调试语句。

【问题讨论】:

    标签: python regex sublimetext3 lookahead negative-lookahead


    【解决方案1】:

    根本原因

    (?=^\s*) 是一个正向预测,它匹配行首(在 SublimeText 中,^ 默认匹配行首),然后是 0+ 个空格(即 @ 987654326@ 根本不需要匹配任何文本!)。

    因此,如果 print_debug 位于字符串的开头,则您的 (?=^\s*)print_debug 模式与 print_debug 匹配(注意 (?!^) 的工作方式与 (?<!^) 相同,因为 ^ 是零宽度断言)。

    解决方案

    由于 SublimeText 正则表达式不支持可变宽度lookbehind,您可以利用 \K 匹配重置运算符

    ^\s*\Kprint_debug
    

    regex demo

    详情

    • ^ - 行首
    • \s* - 零个或多个空格(可以替换为 \h* 以仅匹配水平空格)
    • \K - 省略到目前为止匹配的整个文本
    • print_debug - 文字字符串。

    【讨论】:

      【解决方案2】:

      我相信实际上是你的积极前瞻把事情搞砸了,而不是^。我认为你真正想要的是一个原子组(http://www.regular-expressions.info/atomic.html):

      (?>^\s*)print_debug
      

      这在每一行都显示了我的匹配项(我什至在 Sublime 中对其进行了测试)。

      【讨论】:

      【解决方案3】:

      (?=^\s*)print_debug 表示在匹配位置不仅print_debug 必须匹配,而且^\s*

      匹配的位置是“print_debug”的开头和带有可选空白的行的开头。所以只有行首的“print_debug”匹配。

      如果您想确保print_debug之前只有空白,您应该使用后视:(?<=^\s*)print_debug

      【讨论】:

      • 您的后视功能不起作用:* 后视内的量词使其宽度不固定,regex101.com/r/FmiKiY/2
      • 是的,在这种正则表达式风格中,您不能在后视中使用可变宽度匹配...
      猜你喜欢
      • 1970-01-01
      • 2021-12-04
      • 1970-01-01
      • 2011-09-12
      • 2015-08-30
      • 2012-09-01
      • 2016-11-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多