[英]REGEX Remove from end of string
我有以下字符串:
x = r"""<FNT size='9'>" & [FacilityID] & " " & [DIAMETER] & "</FNT>"""
使用正則表達式或類似的表達式動態嘗試以獲得以下結果:
[FacilityID] & " " & [DIAMETER]
無法強化最終結果。
我有這個要刪除的字符串從第一個[
b = re.sub(r'^.*?\&\s', '', x)
但是我不知道如何從右到左進行與第一個]相反的操作。
我想我需要使用$符號,但我無法使用它,謝謝
如果您真的只想要第一個[
至最后一個]
,則甚至不需要正則表達式,只需index
和lastindex
。
x = r"""<FNT size='9'>" & [FacilityID] & " " & [DIAMETER] & "</FNT>"""
open = x.find("[")
close = x.rfind("]")
print(x[open:close + 1])
搜索第一個打開的方bracket
,然后將所有字符放到下一個關閉的方bracket
,然后將所有字符放到最后一個關閉的方bracket
:
x = r"""<FNT size='9'>" & [FacilityID] & " " & [DIAMETER] & "</FNT>"""
x = re.findall("\[.*?\].*?\]", x)[0]
將x
修改為:
'[FacilityID] & " " & [DIAMETER]'
你可以用
\[.+\]
# match [, anything else, backtrack to the first ] found
除了刪除所有內容 ,您還可以提取所需的輸出 。
Python
:
import re string = """ <FNT size='9'>" & [FacilityID] & " " & [DIAMETER] & "</FNT> <FNT size='9'>" & [anything else] & " " & [something here] & "</FNT> """ rx = re.compile(r'\\[.+\\]') matches = [match.group(0) for match in rx.finditer(string)] print(matches) # ['[FacilityID] & " " & [DIAMETER]', '[anything else] & " " & [something here]']
參見regex101.com上的演示 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.