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

UnL*_*TeD -3 python regex string python-2.7

我需要在python中使用正则表达式来获取{}中的所有单词

a = 'add {new} sentence {with} this word'
Run Code Online (Sandbox Code Playgroud)

re.findall的结果应该是[new,with]

谢谢

ale*_*cxe 6

试试这个:

>>> import re
>>> a = 'add {new} sentence {with} this word'
>>> re.findall(r'\{(\w+)\}', a)
['new', 'with']
Run Code Online (Sandbox Code Playgroud)

另一种方法Formatter:

>>> from string import Formatter
>>> a = 'add {new} sentence {with} this word'
>>> [i[1] for i in Formatter().parse(a) if i[1]]
['new', 'with']
Run Code Online (Sandbox Code Playgroud)

另一种方法split():

>>> 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']
Run Code Online (Sandbox Code Playgroud)

你甚至可以使用string.Template:

>>> class MyTemplate(string.Template):
...     pattern = r'\{(\w+)\}'
>>> a = 'add {new} sentence {with} this word'
>>> t = MyTemplate(a)
>>> t.pattern.findall(t.template)
['new', 'with']
Run Code Online (Sandbox Code Playgroud)