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

Universal match and replace a pattern of arbitray length where only the beginning and end are known

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

假设我有一个文本,其中多次出现这种模式:

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

我想用

替换这个图案的每一次出现

Whatever.

问题是 - 这个模式可以是任意长度(除了它的开头和结尾),它可以延伸到一行或多行,并且可以包含任意数量的特殊字符,包括单字符和双字符引号、所有类型的斜杠、HTML 标签和其他诸如此类的东西。

表达式将必须寻找起始短语,收集它以及该短语之后的所有内容,无论需要多长时间以及途中的 "stuff" 是什么类型,直到遇到结束短语,也收集它并用替换字符串替换整个东西;然后再做一次,直到遇到文本的结尾。

是否有任何一个 (python) 通用表达式可以完成这种工作?

这只是从此处的正则表达式生成的 - 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.