如何使用正则表达式捕获并替换包含特定模式的行中的所有模式

3
我正在尝试设置一个正则表达式,以允许我将两个空格替换为一个制表符,但仅限于包含特定模式的行。
foo: here  is  some  sample  text
bar: here  is  some  sample  text

在上面的例子中,我想用一个制表符来替换任何由两个空格组成的组,但只在包含“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

我可以执行替换三次以获得所需的结果,但我正在处理可能包含数百个这些序列的文本文件。 我使用Sublime Text,但我很确定它使用PCRE作为其Regex。
2个回答

3

这个同样有效

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

https://regex101.com/r/vnM649/1
or
https://regex101.com/r/vnM649/2

Explained

 (?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

能否将此代码翻译成Python的可运行代码?

可以。

构造函数\G提供了在单个正则表达式中完成所有操作的能力。Python的regex模块支持它,但re模块不支持。如果使用re模块,则需要进行2个步骤。

第一步是匹配出bar所在的行,
然后将其传递给回调函数以将所有双倍空格替换为制表符,
然后将其作为替换返回给调用者。

以下是示例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)

请不要破坏您的帖子。 - Baum mit Augen

0

这个会起作用:

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

(注意“find”正则表达式末尾的2个空格),但它会在foo行末添加一个制表符。
这里查看PCRE演示。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接