I have a paragraph like this:
paragraph = "Dear {{userName}},
You have been registered successfully. Our Manager {{managerName}} will contact soon.
Thanks"
I need to parse all the strings within {{}}. There could be many more like that in the paragraph.
I tried this solution:
result = re.search('{{(.*)}}',paragraph)
print(result.group(1))
# output is 'userName}} {{ManagerName'
Output I wanted is:
["userName","managerName",....]
Please help.
Thanks
Use re.findall
Ex:
import re
paragraph = """Dear {{userName}},
You have been registered successfully. Our Manager {{managerName}} will contact soon.
Thanks"""
print( re.findall(r"\{\{(.*?)\}\}", paragraph) )
Output:
['userName', 'managerName']
Here is an alternative solution without needing regex. You can just find the positions of {{
and }}
using str.find()
.
closebrace = 0
while True:
openbrace = paragraph.find('{{', closebrace)
if openbrace == -1:
break
closebrace = paragraph.find('}}', openbrace)
# You now have the positions of open and close braces,
# check if close brace is -1, then do whatever you want with them
print(openbrace, closebrace)
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.