gpt4 book ai didi

python - 替换以相同模式开头的连续行 block

转载 作者:行者123 更新时间:2023-12-01 23:05:45 25 4
gpt4 key购买 nike

我想匹配(并用自定义替换函数替换)所有以 foo 开头的连续 行的每个 block 。这几乎可以工作:

import re

s = """bar6387
bar63287
foo1234
foohelloworld
fooloremipsum
baz
bar
foo236
foo5382
bar
foo879"""

def f(m):
print(m)

s = re.sub('(foo.*\n)+', f, s)
print(s)
# <re.Match object; span=(17, 53), match='foo1234\nfoohelloworld\nfooloremipsum\n'>
# <re.Match object; span=(61, 76), match='foo236\nfoo5382\n'>

但它无法识别最后一个 block ,显然是因为它是最后一行并且末尾没有\n

是否有更简洁的方法来匹配以相同模式 foo 开头的一行或多行的 block ?

最佳答案

这是一个re.findall方法:

s = """bar6387
bar63287
foo1234
foohelloworld
fooloremipsum
baz
bar
foo236
foo5382
bar
foo879"""

lines = re.findall(r'^foo.*(?:\nfoo.*(?=\n|$))*', s, flags=re.M)
print(lines)
# ['foo1234\nfoohelloworld\nfooloremipsum',
'foo236\nfoo5382',
'foo879']

上面的正则表达式以多行模式运行,并说要匹配:

^                     from the start of a line
foo "foo"
.* consume the rest of the line
(?:\nfoo.*(?=\n|$))* match newline and another "foo" line, 0 or more times

编辑:

如果您需要替换/删除这些 block ,请使用相同的模式与 re.sub 和 lambda 回调:

output = re.sub(r'^foo.*(?:\nfoo.*(?=\n|$))*', lambda m: "BLAH", s, flags=re.M)
print(output)

这打印:

bar6387
bar63287
BLAH
baz
bar
BLAH
bar
BLAH

关于python - 替换以相同模式开头的连续行 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70923714/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com