繁体   English   中英

使用Regex在Python中的两个字符串之间更改文本

[英]Change a text between two strings in Python with Regex

我发现了几个类似的问题,但我的问题无法适合其中任何一个。 我尝试在文本中的其他两个字符串之间查找并替换一个字符串。

reg = "%s(.*?)%s" % (str1,str2)
r = re.compile(reg,re.DOTALL)
result = r.sub(newstring, originaltext)

问题是上面的代码也替换了str1str2 ,而我只想替换它们之间的文本。 很明显我想念什么吗?

更新:

我简化了示例:

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

在您的正则表达式中结合使用环顾四周

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

工作演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM