[英]Python: Remove all characters outside of first curly braces
如果我有這樣的字符串:
text to remove { first text { group } { group2 } } more text to remove
我只想專門刪除不在第一個大括號內的文本,以獲得如下所示的內容:
{ first text { group } { group2 } }
要在正則表達式中執行此操作,我不確定如何僅針對花括號的第一次迭代而不是嵌套括號進行指定。
也許有比使用正則表達式更簡單的方法。 但是,要刪除的文本的長度可能會有所不同。
您可以使用search
和group
:
>>> re.search('{.*}',s).group(0)
'{ first text { group } { group2 } }'
>>>
或findall
:
>>> re.findall('{.*}',s)[0]
'{ first text { group } { group2 } }'
>>>
除了regex,您還可以使用find
和rfind
,它比regex更有效。
str = 'text to remove { first text { group } { group2 } } more text to remove'
begin, end = str.find('{'), str.rfind('}')
filtered_str = str[begin: end+1]
print(filtered_str)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.