如何在看起来像这样的字符串中找到所有子字符串{{ test_variable }?
s = "hi {{ user }}, samle text, {{ test_variable } 2100210121, testing"
Run Code Online (Sandbox Code Playgroud)
我的尝试:
finds = re.findall(r"(\{{ .*?\}$)", s)
但是此正则表达式返回的子字符串也以}}而不是结尾,}所以我看到不需要{{ user }}的结果
尝试使用以下正则表达式模式:
\{\{\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)
| 归档时间: |
|
| 查看次数: |
56 次 |
| 最近记录: |