例如,我需要 python 中的正则表达式来获取 {} 中的所有单词
a = 'add {new} sentence {with} this word'
re.findall 的结果应该是 [new, with]
谢谢
例如,我需要 python 中的正则表达式来获取 {} 中的所有单词
a = 'add {new} sentence {with} this word'
re.findall 的结果应该是 [new, with]
谢谢
尝试这个:
>>> 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']
>>> import re
>>> re.findall(r'(?<={).*?(?=})', 'add {new} sentence {with} this word')
['new', 'with']