我正在尝试设置一个正则表达式,允许我用制表符替换 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 作为其正则表达式。
最佳答案
这也行
(?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
可以将其转换为与 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)
关于regex - 如何使用正则表达式捕获和替换包含单独模式的行上的所有模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55505769/