簡體   English   中英

使用 re.sub() 從匹配的模式中刪除空格

[英]Remove spaces from matched patterns using re.sub()

我正在嘗試使用re.sub()從匹配模式中刪除空格

我的文字將是這樣的:

text = Hi my name is Bob and I am taking courses ABC 123 and EFG123

現在我的意圖是找到課程,並刪除它們之間的空格。

我的正則表達式模式是:

regex = '[a-zA-Z]{2,4}[ ]?\d{2,4}'

我正在嘗試刪除ABC 123中的空間,目前我正在使用:

text = re.sub(r'[a-zA-Z]{2,4}[ ]?\d{2,4}', '\\1\\2', text)

但是,我收到錯誤:

error: invalid group reference 1 at position 1

如何刪除那里的空間,我嘗試用一個空格替換整個東西,我可以確認正則表達式確實找到了模式,但是,我收到以下錯誤。

這有效:

text = "Hi my name is Bob and I am taking courses ABC 123 and EFG123"
>>> re.sub(r'([A-z]{2,4})\W?(\d{2,4})', '\\1\\2', text)
'Hi my name is Bob and I am taking courses ABC123 and EFG123'

您沒有在正則表達式模式中指定捕獲組( ([Az]{2,4})(\d{2,4}) ),因此出現錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM