Aug-04-2022, 11:26 PM
You can get the start and end positions of any pattern with re
pattern = re.compile('x:') # this returns a tuple with the position of the pattern in your string start_stop = pattern.search(astring).span()You could do it like this:
import re astring = 'aaaax:bbbbbbbbbbbbbbby:cccccccccccccccccccz:ddddddddddddddddd' myvars = ['x:', 'y:', 'z:', 'dog'] length = 10 results = [] for item in myvars: pattern = re.compile(item) # find where the search string starts start = pattern.search(astring) # if the pattern is not found search returns None if not start == None: #get the span tuple tup = start.span() # change the tuple to get what you want newtup = (tup[0] + 2, tup[1] + length) # slice the string wanted = astring[newtup[0]:newtup[1]] results.append(wanted)