如何使用Regex捕获和替换包含单独模式的行上的所有模式

问题描述 投票:2回答:2

我正在尝试设置一个正则表达式,允许我用制表符替换2个空格,但仅限于包含特定模式的行。

foo: here  is  some  sample  text
bar: here  is  some  sample  text

在上面的例子中,我想用一个制表符替换任何2个空格的组,但仅限于包含“bar”的行:

foo: here  is  some  sample  text
bar: here    is    some    sample    text

我得到的最接近的一直是使用这个:

Find: ^(\s.*)(bar)(.*)  (.*)
Replace: \1\2\3\t\4

但是,这一次只能替换一组两个空格,所以我最终得到这个:

foo: here  is  some  sample  text
bar: here  is  some  sample    text

我可以再执行3次替换并得到我想要的结果,但我正在处理可能包含数百个这些序列的文本文件。

我正在使用Sublime Text,但我很确定它使用PCRE作为其正则表达式。

regex sublimetext3 pcre
2个回答
2
投票

这也有效

(?m-s)(?:^(?=.*\bbar\b)|(?!^)\G).*?\K[ ]{2}

https://regex101.com/r/vnM649/1 要么 https://regex101.com/r/vnM649/2

解释

 (?m-s)               # Multi-line mode, not Dot-All mode
 (?:
      ^                    # Only test at BOL for 'bar'
      (?= .* \b bar \b )
   |                     # or,
      (?! ^ )              # Not BOL, must have found 2 spaces in this line before
      \G                   # Start where last 2 spaces left off
 )
 .*?                  # Minimal any character (except newline)
 \K                   # Ignore anything that matched up to this point
 [ ]{2}               # 2 spaces to replace with a \t

possible to translate this to work with Python?

是。

\G结构提供了在单程正则表达式中完成所有操作的能力。 Python regex模块支持它,但不是它的re模块。如果使用re模块,则需要分两步完成。

首先是匹配bar所在的线 然后将其传递给回调以替换所有double 空格到选项卡,然后将其作为替换返回 回到来电者。

示例Python代码:

https://rextester.com/AYM96859

 #python 2.7.12

 import re

 def replcall(m):
     contents = m.group(1)
     return re.sub( r'[ ]{2}',"\t", contents )

 str = (
 r'foo: here  is  some  sample  text' + "\n"
 r'bar: here    is    some    sample    text' + "\n"
 )

 newstr = re.sub( r'(?m)(^(?=.*\bbar\b)(?=.*[ ]{2}).*)', replcall, str )

 print newstr

获得该线的正则表达式扩展了:

 (?m)
 (                             # (1 start)
      ^ 
      (?= .* \b bar \b )
      (?= .* [ ]{2} )
      .* 
 )                             # (1 end)

0
投票

这将有效:

Find: (^(?!.*bar).*)|  
Replace: \1\t

(注意“查找”正则表达式末尾的2个空格)但它会在foo行的末尾添加一个制表符。

请参阅here一个PCRE演示。

© www.soinside.com 2019 - 2024. All rights reserved.