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

时间:2013-07-30 06:51:31

标签: python regex string python-2.7

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

a = 'add {new} sentence {with} this word'

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

谢谢

2 个答案:

答案 0 :(得分:6)

试试这个:

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

使用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']

使用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']

您甚至可以使用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']

答案 1 :(得分:1)

>>> import re
>>> re.findall(r'(?<={).*?(?=})', 'add {new} sentence {with} this word')
['new', 'with']