简体   繁体   English

如何获取两个特定单词前后的所有字符串?

[英]How to get all the string after and before two specific words?

I want to replace all the string after "my;encoded;image:" (which is the base64 data of the image) and i want to stop before the word "END", but the following code is replacing also the two strings "my;encoded;image:" and "END".我想替换“my;encoded;image:”之后的所有字符串(这是图像的 base64 数据)并且我想在“END”这个词之前停止,但是下面的代码也替换了两个字符串“my ;编码;图像:”和“END”。 Any suggestions?有什么建议么?

import re
re.sub("my;encoded;image:.*END","random_words",image,flags=re.DOTALL)

NB: a simple way could be to use replacement but i want to use regex in my case Thanks注意:一种简单的方法可能是使用替换,但我想在我的情况下使用正则表达式谢谢

You can use a non-greedy regex to split the string into three groups.您可以使用非贪婪的正则表达式将字符串分成三组。 Then replace the second group with your string:然后用您的字符串替换第二组:

import re

x = re.sub(r'(.*my;encoded;image:)(.*?)(END.*)', r"\1my string\3", image)

print(x)

You can use f-strings with Python 3.6 and higher:您可以在 Python 3.6 及更高版本中使用 f 字符串:

replacement = "hello"
x = re.sub(r'(.*my;encoded;image:)(.*?)(END.*)', fr'\1{replacement}\3', image)

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

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