通用匹配和替换任意长度的模式,其中只有开始和结束是已知的

2024-04-24 03:26:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我知道这个问题的一些变体已经被讨论过了,但它们似乎并不像以前那样普遍适用。因此这个问题

假设我有一个文本,在其中出现了好几次,这个模式:

Let's start! ... blah, blah, blah... This is the end, my friend.

我想用

Whatever.

问题是-这个模式可以是任意长度(除了它的开始和结束),它可以延伸到一行或多行,可以包含任意数量的特殊字符,包括单引号和双引号,所有类型的斜杠,HTML标记,和其他什么

表达式必须寻找起始短语,收集它以及该短语后面的所有内容,不管需要多长时间,也不管什么类型的“stuff”正在进行中,直到它遇到结束短语,也收集该短语,并用替换字符串替换整件事;然后再做一次,直到碰到课文的结尾

有没有一个(python)通用表达式可以完成这种工作


Tags: the文本friend类型is表达式my模式
1条回答
网友
1楼 · 发布于 2024-04-24 03:26:51

这是从regex生成的-https://regex101.com/r/J8um0E/3/

# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility

import re

regex = r"Let's start(.*[\r\n])*.*my friend\."

test_str = ("Let's start! ... blah, blah, blah...\n"
    "How much longer? It's joe's place, isn't it?\n"
    "This is the end, my friend.")

subst = "Whatever."

# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(regex, subst, test_str, 0, re.MULTILINE)

if result:
    print (result)

# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.

相关问题 更多 >