Python:反复查找两个特殊字符之间的字符串

时间:2018-08-09 06:30:08

标签: python regex

我有一个这样的段落:

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",....]

请帮助。

谢谢

2 个答案:

答案 0 :(得分:5)

使用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']

答案 1 :(得分:-1)

这是不需要正则表达式的替代解决方案。您可以使用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)