我想刪除所有括號和括號內的文本。我使用正則表達式Python的正則表達式只適用於子字符串匹配,但不是整個字符串
re.sub(r'\(.*\) | \[.*\]', '', text)
這個工程的東西,如:
import re
text = 'the (quick) brown fox jumps over the [lazy] dog'
print re.sub(r'\(.*\) | \[.*\]', '', text)
> the brown fox jumps over the dog
text = '(the quick) brown fox jumps over the [lazy] dog'
print re.sub(r'\(.*\) | \[.*\]', '', text)
> brown fox jumps over the dog
但是,當整個字符串的正則表達式
text = '[the quick brown fox jumps over the lazy dog]'
print re.sub(r'\(.*\) | \[.*\]', '', text)
> [the quick brown fox jumps over the lazy dog]
> # This should be '' (the empty string) #
匹配失敗我要去哪裏錯了?
雖然我會小心貪婪的匹配。如果你的文本中有一個隨機的「)」,可能只是一個獨立的符號,那麼這個正則表達式就會擺脫它們之間的一切。例如。 '「這是一個帶有a)符號的(小)示例文本」'會變成'「這是一個符號」'。也許使用不情願的比賽? (請參閱我的回答編輯) – gowrath
@gowrath這是一個重要的說明。在我的情況下,我很有信心,因爲我格式化了數據,但在一般情況下,這是必須處理的東西 – marcman