我正在寻找一个python正则表达式,它将在pattern
和replace_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)
答案 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_pattern
到re.sub
函数。
(?<!\S)pattern(?!\S)(?=(?:(?!(?<!\S)(?:start|end)(?!\S)).)*?(?<!\S)end(?!\S))
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'