如何使用正则表达式在 python 字符串中找到 str.format 的所有占位符? [英] How can I find all placeholders for str.format in a python string using a regex?
问题描述
我正在创建一个使用用户指定格式重命名文件的类.此格式将是一个简单的字符串,其 str.format
方法将被调用以填充空格.
I'm creating a class that renames a file using a user-specified format. This format will be a simple string whose str.format
method will be called to fill in the blanks.
事实证明,我的过程需要提取包含在大括号中的变量名称.例如,一个字符串可能包含 {user}
,它应该产生 user
.当然,单个字符串中会有几组大括号,我需要按照它们出现的顺序获取每组的内容并将它们输出到列表中.
It turns out that my procedure will require extracting variable names contained in braces. For example, a string may contain {user}
, which should yield user
. Of course, there will be several sets of braces in a single string, and I'll need to get the contents of each, in the order in which they appear and output them to a list.
因此,"{foo}{bar}"
应该产生 ['foo', 'bar']
.
我怀疑最简单的方法是使用 re.split
,但我对正则表达式一无所知.有人可以帮我吗?
I suspect that the easiest way to do this is to use re.split
, but I know nothing about regular expressions. Can someone help me out?
提前致谢!
推荐答案
Using re.findall()
:
In [5]: import re
In [8]: strs = "{foo} spam eggs {bar}"
In [9]: re.findall(r"{(\w+)}", strs)
Out[9]: ['foo', 'bar']
这篇关于如何使用正则表达式在 python 字符串中找到 str.format 的所有占位符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!