首页 > 解决方案 > Python:重复查找两个特殊字符之间的字符串

问题描述

我有这样一段:

paragraph = "Dear {{userName}},

You have been registered successfully. Our Manager {{managerName}} will contact soon.

Thanks"

我需要解析 {{}} 中的所有字符串。在该段落中可能还有更多类似的内容。

我试过这个解决方案:

result = re.search('{{(.*)}}',paragraph)
print(result.group(1))
# output is 'userName}} {{ManagerName' 

我想要的输出是:

["userName","managerName",....]

请帮忙。

谢谢

标签: pythonregex

解决方案


利用re.findall

前任:

import re

paragraph = """Dear {{userName}},
You have been registered successfully. Our Manager {{managerName}} will contact soon.
Thanks"""

print( re.findall(r"\{\{(.*?)\}\}", paragraph) )

输出:

['userName', 'managerName']

推荐阅读