Python正则表达式匹配{}中的所有单词

Python正则表达式匹配{}中的所有单词,python,regex,string,python-2.7,Python,Regex,String,Python 2.7,例如,我需要python中的正则表达式来获取{}中的所有单词 a = 'add {new} sentence {with} this word' 使用re.findall的结果应为[新的,带有] 谢谢试试这个: >>> import re >>> a = 'add {new} sentence {with} this word' >>> re.findall(r'\{(\w+)\}', a) ['new', 'with'] 使用格式化程序

例如,我需要python中的正则表达式来获取{}中的所有单词

a = 'add {new} sentence {with} this word'
使用re.findall的结果应为[新的,带有]

谢谢

试试这个:

>>> import re
>>> a = 'add {new} sentence {with} this word'
>>> re.findall(r'\{(\w+)\}', a)
['new', 'with']
使用格式化程序的另一种方法:

另一种使用拆分的方法:

您甚至可以使用string.Template:


你已经试过什么了?什么不起作用?可能是{.*.}!!!!
>>> from string import Formatter
>>> a = 'add {new} sentence {with} this word'
>>> [i[1] for i in Formatter().parse(a) if i[1]]
['new', 'with']
>>> import string
>>> a = 'add {new} sentence {with} this word'
>>> [x.strip(string.punctuation) for x in a.split() if x.startswith("{") and x.endswith("}")]
['new', 'with']
>>> class MyTemplate(string.Template):
...     pattern = r'\{(\w+)\}'
>>> a = 'add {new} sentence {with} this word'
>>> t = MyTemplate(a)
>>> t.pattern.findall(t.template)
['new', 'with']
>>> import re
>>> re.findall(r'(?<={).*?(?=})', 'add {new} sentence {with} this word')
['new', 'with']