2013-07-30 2 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']