2013-07-30 120 views
-3

我需要在Python正则表达式来获取在{}例如Python的正则表达式匹配{}

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

结果与re.findall所有的话应该是[新的,具有]

所有单词

感谢

+2

你有什么已经尝试过?什么不行? – soon

+0

可能是'{(。*?)}'!!!! – NINCOMPOOP

回答

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