-3

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

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

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

谢谢

4

2 回答 2

7

尝试这个:

>>> 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']
于 2013-07-30T06:55:17.340 回答
1
>>> import re
>>> re.findall(r'(?<={).*?(?=})', 'add {new} sentence {with} this word')
['new', 'with']
于 2013-07-30T06:55:28.793 回答