-3
我需要在Python正則表達式來獲取在{}例如Python的正則表達式匹配{}
a = 'add {new} sentence {with} this word'
結果與re.findall所有的話應該是[新的,具有]
所有單詞感謝
我需要在Python正則表達式來獲取在{}例如Python的正則表達式匹配{}
a = 'add {new} sentence {with} this word'
結果與re.findall所有的話應該是[新的,具有]
所有單詞感謝
試試這個:
>>> 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']
你有什麼已經嘗試過?什麼不行? – soon
可能是'{(。*?)}'!!!! – NINCOMPOOP