简体   繁体   中英

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". 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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