我发现了几个类似的问题,但我无法解决任何问题.我尝试在文本中的两个其他字符串之间查找并替换字符串.
reg = "%s(.*?)%s" % (str1,str2)
r = re.compile(reg,re.DOTALL)
result = r.sub(newstring, originaltext)
Run Code Online (Sandbox Code Playgroud)
问题是,上面的代码也更换str1和str2,而我想只替换它们之间的文本.显然我想念的东西?
更新:
我简化了例子:
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
Run Code Online (Sandbox Code Playgroud)
结果是abcdefstackexchangeqrstuvwxyz我需要的结果abcdefghstackexchangeopqrstuvwxyz
在正则表达式中使用外观的组合.
reg = "(?<=%s).*?(?=%s)" % (str1,str2)
Run Code Online (Sandbox Code Playgroud)
说明:
Lookarounds是零宽度断言.它们不会消耗字符串上的任何字符.
(?<= # 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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1601 次 |
| 最近记录: |