如何刪除<ref> *some text*</ref>
以及ref
本身的文本?用正則表達式替換某個詞的某個部分
'...and so on<ref>Oxford University Press</ref>.'
re.sub(r'<ref>.+</ref>', '', string)
只有<ref>
如果 <ref>
後面是空白
編輯刪除:它有不便做字邊界我想......還是?
EDIT2我需要的是,它將數學最後(閉幕)</ref>
哪怕是一個換行符。
如何刪除<ref> *some text*</ref>
以及ref
本身的文本?用正則表達式替換某個詞的某個部分
'...and so on<ref>Oxford University Press</ref>.'
re.sub(r'<ref>.+</ref>', '', string)
只有<ref>
如果 <ref>
後面是空白
編輯刪除:它有不便做字邊界我想......還是?
EDIT2我需要的是,它將數學最後(閉幕)</ref>
哪怕是一個換行符。
我並沒有真正看到你的問題,因爲粘貼的代碼將刪除字符串的<ref>...</ref>
部分。但是,如果你的意思是,和空裁判標籤不會被刪除:。
re.sub(r'<ref>.+</ref>', '', '...and so on<ref></ref>.')
然後,你需要做的是改變什麼+與*
A +意味着一個或多個,而*手段零或更多。
從http://docs.python.org/library/re.html:
'.' (Dot.) In the default mode, this matches any character except a newline.
If the DOTALL flag has been specified, this matches any character including
a newline.
'*' Causes the resulting RE to match 0 or more repetitions of the preceding
RE, as many repetitions as are possible. ab* will match ‘a’, ‘ab’, or ‘a’
followed by any number of ‘b’s.
'+' Causes the resulting RE to match 1 or more repetitions of the preceding
RE. ab+ will match ‘a’ followed by any non-zero number of ‘b’s; it will
not match just ‘a’.
'?' Causes the resulting RE to match 0 or 1 repetitions of the preceding RE.
ab? will match either ‘a’ or ‘ab’.
你可能要保持謹慎,不要刪除了一大堆的文字,只是因爲有一個以上的收盤</ref>
秒。下面的正則表達式是在我看來,更準確:
r'<ref>[^<]*</ref>'
這將阻止「貪婪」匹配。
順便說一句:有一個偉大的工具稱爲正則表達式教練來分析和測試你的正則表達式。你可以在:http://www.weitz.de/regex-coach/
編輯:忘了在第一段添加代碼標籤。
你可以做一個花哨的正則表達式來完成你想要的東西,但是你需要使用DOTALL和非貪婪的搜索,並且你需要了解正則表達式在一般情況下的工作方式,而你不需要。
你最好的選擇是使用字符串方法而不是正則表達式,這是更Python反正:
while '<reg>' in string:
begin, end = string.split('<reg>', 1)
trash, end = end.split('</reg>', 1)
string = begin + end
如果你想成爲非常通用的,允許在標籤的標籤或空格和屬性的怪資本,你也不應該這樣做,但要投資學習一個html/xml解析庫。 lxml目前似乎被廣泛推薦並得到很好的支持。
如果您嘗試使用正則表達式執行此操作,則代碼爲world of trouble。您正在有效地嘗試解析某些內容,但解析器無法完成任務。
整個字符串匹配貪婪地吃可能太多,因爲在這個例子中:
<ref>SDD</ref>...<ref>XX</ref>
你最終cleraning了整個中東。
你真的想要一個解析器,就像Beautiful Soup。
from BeautifulSoup import BeautifulSoup, Tag
s = "<a>sfsdf</a> <ref>XX</ref> || <ref>YY</ref>"
soup = BeautifulSoup(s)
x = soup.findAll("ref")
for z in x:
soup.ref.replaceWith('!')
soup # <a>sfsdf</a> ! || !
以及如果關閉''在新行?我該如何處理? – Gusto 2010-11-10 22:12:33
顯然有一個標誌(re.DOTALL),它使''。匹配所有字符_including_換行符。但是這似乎不適用於python2.6中的重新模塊。 *更新:*看看docs.python.org/library/re.html它說re.sub:在版本2.7,3.1更改:添加了可選的標誌參數。 – 2010-11-10 22:23:50
我已經試過了(re.DOTALL)'應用re.sub(R「(S) *?」'但它失去控制和消除過多,超過了文字的一半 - 這是絕對錯誤的任何其他的想法從http://docs.python.org/library/re.html – Gusto 2010-11-10 22:34:22