2011-11-13 45 views
-1

我有以下語法文件:Python的正則表達式匹配和刪除特定圖案

<whitespace_sequence><string><whitespace_sequence><--More--><whitespace_sequence><string_sequence><newline> 

使用Python(2.4),我想刪除序列:

"<whitespace_sequence><--More--><whitespace_sequence>" from the above grammar. 

我我正在使用以下正則表達式模式:

x = re.compile("(\s+)("--More--")(\s+)") 

但它不匹配我需要刪除的序列。

+3

示例字符串比臨時語法更有用。 – Tomalak

+0

這真的是你跑的代碼嗎?它會拋出一個NameError異常。 – interjay

回答

1

它看起來像你的正則表達式的問題是雙引號。如果沒有他們,它工作正常:

>>> sample = ' string --More-- anotherstring \n' 
>>> import re 
>>> re.search(r'(\s+)(--More--)(\s+)', sample).groups() 
(' ', '--More--', ' ') 

FWIW,這裏是直接從樣本串開發正則表達式一個很好的資源: http://txt2re.com/

另一個很好的資源,以瞭解更多關於正則表達式是:http://www.regular-expressions.info/