我发现了几个类似的问题,但我无法将我的问题与其中任何一个相匹配。我尝试查找并替换文本中其他两个字符串之间的字符串。
reg = "%s(.*?)%s" % (str1,str2)
r = re.compile(reg,re.DOTALL)
result = r.sub(newstring, originaltext)
问题是上面的代码也替换了str1
and str2
,而我只想替换它们之间的文本。我显然想念一些东西吗?
Update:
我简化了例子:
text = 'abcdefghijklmnopqrstuvwxyz'
str1 = 'gh'
str2 = 'op'
newstring = 'stackexchange'
reg = "%s(.*?)%s" % (str1,str2)
r = re.compile(reg,re.DOTALL)
result = r.sub(newstring, text)
print result
结果是abcdefstackexchangeqrstuvwxyz
而我需要abcdefghstackexchangeopqrstuvwxyz
使用组合环顾四周 http://www.rexegg.com/regex-disambiguation.html#lookaround在你的正则表达式中。
reg = "(?<=%s).*?(?=%s)" % (str1,str2)
解释:
环视是零宽度断言。它们不消耗字符串上的任何字符。
(?<= # look behind to see if there is:
gh # 'gh'
) # end of look-behind
.*? # any character except \n (0 or more times)
(?= # look ahead to see if there is:
op # 'op'
) # end of look-ahead
工作演示 https://eval.in/169213
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)