如何在以{{开头并以}结尾的字符串中查找所有子字符串

dev*_*fan 2 python

如何在看起来像这样的字符串中找到所有子字符串{{ test_variable }

s = "hi {{ user }}, samle text, {{ test_variable } 2100210121, testing"
Run Code Online (Sandbox Code Playgroud)

我的尝试:

finds = re.findall(r"(\{{ .*?\}$)", s)

但是此正则表达式返回的子字符串也以}}而不是结尾,}所以我看到不需要{{ user }}的结果

Tim*_*sen 7

尝试使用以下正则表达式模式:

\{\{\s*([^{} ]+)\s*\}(?=[^}]|$)
Run Code Online (Sandbox Code Playgroud)

这与您所使用的类似,但是在结束后使用正向先行}以确保后面的不是另一个},也不是字符串的结尾。

\{\{\s*([^{} ]+)\s*\}   match desired string as {{ STRING }
(?=[^}]|$)              then assert that what follows the final } is NOT
                        another }, or is the end of the entire string
Run Code Online (Sandbox Code Playgroud)

脚本:

s = "hi {{ user }}, samle text, {{ test_variable } 2100210121, testing"
matches = re.findall(r'{{\s*([^{} ]+)\s*}(?=[^}]|$)', s)
print(matches)

['test_variable']
Run Code Online (Sandbox Code Playgroud)

  • @MarkMeyer不,您不知道,但这还是一个好主意。无论如何,要使正则表达式可以在测试工具上运行,您可能仍必须对其进行转义。 (2认同)