so actually the requested result is "For each "|BS| group remove as many chars before that group as many times |BS| is present in that group"
#!/usr/bin/python3 import re strings = ['it |BS||BS||BS|this is one|BS||BS||BS|an example', 'it |BS|this is an example', 'it |BS||BS|this is an example', 'it |BS||BS||BS|this is an example', 'it |BS||BS||BS||BS|this is an example'] ptrn = re.compile(r'[\w ]?\|BS\|') for string in strings: print(string) while True: after_sub = ptrn.sub('', string, count=1) if string == after_sub: break else: string = after_sub print(string) print('\n')
Output:it |BS||BS||BS|this is one|BS||BS||BS|an example
this is an example
it |BS|this is an example
itthis is an example
it |BS||BS|this is an example
ithis is an example
it |BS||BS||BS|this is an example
this is an example
it |BS||BS||BS||BS|this is an example
this is an example