I have weird list of items and lists like this with |
as a delimiters and {{ }}
as a parenthesis. It looks like this:
| item1 | item2 | item3 | {{Ulist1 | item4 | item5 | {{Ulist2 | item6 | item7 }} | item8 }} | item9 | {{list3 | item10 | item11 | item12 }} | item13 | item14
I want to match items in lists called Ulist*
(items 4-8) using RegEx and replace them with Uitem*
. The result should look like this:
| item1 | item2 | item3 | {{Ulist1 | Uitem4 | Uitem5 | {{Ulist2 | Uitem6 | Uitem7 }} | Uitem8 }} | item9 | {{list3 | item10 | item11 | item12 }} | item13 | item14
Update:
I tried a solution according to this question, but the answer from that question doesn't work, if there is a list
inside of an Ulist
. It is in Python 2.7, specifically my code is:
#!/usr/bin/python
# -*- coding: utf-8 -*-
import regex
def repl(m):
return "".join([x.replace("item", "Uitem") if x.startswith("{{Ulist") else x for x in regex.split(r'\{{2}(?=(\blist\d*))[^\}]*(?:}(?!})[^\}]*)*}}', m.group(0))])
text = "| item1 | item2 | item3 | {{Ulist1 | item4 | item5 | {{Ulist2 | item6 | item7 }} | item8 | {{list4 | item15 | item16 }} | item17 }} | item9 | {{list3 | item10 | item11 | item12 }} | item13 | item14"
rex = r'(\{\{(?=(Ulist\d*))(?>[^}{]|}(?!})|\{(?!\{)|(?1))*}})'
text = regex.sub(rex, repl, text)
print(text)