python重新替换标签之间的所有内容

时间:2014-11-10 12:02:50

标签: python regex replace

我正在寻找一个python正则表达式,它将在patternreplace_pattern之间用start替换所有出现的end

示例:

start fkdsjflsd pattern jdflsdjf pattern end

将会是

start fkdsjflsd replace_pattern jdflsdjf replace_pattern end

我已设法在for循环中执行此操作:

pattern = 'start(?P<before1>.*)' + pattern
while re.findall(pattern, content, flags=re.DOTALL | re.IGNORECASE):

    repl = 'start\g<before1>' + replace_pattern
    content = re.sub(pattern, repl, content, flags=re.DOTALL | re.IGNORECASE)

3 个答案:

答案 0 :(得分:1)

\bpattern\b(?=(?:(?!\bend\b|\bstart\b).)*\bend\b(?:(?:(?!\bstart\b|\bend\b).)*\bstart\b(?:(?!\bend\b|\bstart\b).)*\bend\b)*(?:(?!\bstart\b|\bend\b).)*$)

试试这个。看看演示。

http://regex101.com/r/tF5fT5/30

    import re
p = re.compile(ur'pattern(?=(?:(?!\bend\b|\bstart\b).)*\bend\b(?:(?:(?!\bstart\b|\bend\b).)*\bstart\b(?:(?!\bend\b|\bstart\b).)*\bend\b)*(?:(?!\bstart\b|\bend\b).)*$)', re.IGNORECASE)
test_str = u"pattern start fkdsjflsd pattern jdflsdjf pattern end pattern"
subst = u"replace_pattern"

result = re.sub(p, subst, test_str)

答案 1 :(得分:1)

如果开始和结束字符串或正确封闭,那么您可以使用以下正则表达式匹配字符串pattern。然后将匹配的字符串pattern替换为replace_patternre.sub函数。

(?<!\S)pattern(?!\S)(?=(?:(?!(?<!\S)(?:start|end)(?!\S)).)*?(?<!\S)end(?!\S))

DEMO

In [6]: import re

In [7]: s = "pattern foo start fkdsjflsd pattern jdflsdjf pattern end pattern"

In [8]: re.sub(r'(?<!\S)pattern(?!\S)(?=(?:(?!(?<!\S)(?:start|end)(?!\S)).)*?(?<!\S)end(?!\S))', r'replace_pattern', s)
Out[8]: 'pattern foo start fkdsjflsd replace_pattern jdflsdjf replace_pattern end pattern'

答案 2 :(得分:0)

这是一种方式:

>>> import re
>>> a='start fkdsjflsd pattern jdflsdjf pattern end'
>>> re.sub(r'(start\s+.*?)pattern\s+(.*?end)',r'\1 replace_pattern \2',a)
'start fkdsjflsd  replace_pattern jdflsdjf pattern end'