1
如何進行模式匹配,只要它不在HTML標籤內?只匹配不屬於HTML標記的文本的正則表達式? (python)
下面是我的嘗試。任何人都有更好的/不同的方法?
import re
inputstr = 'mary had a <b class="foo"> little loomb</b>'
rx = re.compile('[aob]')
repl = 'x'
outputstr = ''
i = 0
for astr in re.compile(r'(<[^>]*>)').split(inputstr):
i = 1 - i
if i:
astr = re.sub(rx, repl, astr)
outputstr += astr
print outputstr
輸出:
mxry hxd x <b class="foo"> little lxxmx</b>
注:
- 的< [^>] *>模式來匹配HTML標籤顯然是有缺陷的 - 我很快就寫了這一點,並沒有說明引用屬性中的尖括號的可能性(例如'< img alt =「next >」/ >')。它不包括<腳本>或<風格>標籤或評論,或者。
Duplicate:http://stackoverflow.com/questions/181095/regular-expression-to-extract-text-from-html – 2008-12-30 23:35:25