簡體   English   中英

Python正則表達式:BackReference

[英]Python Regular Expression: BackReference

這里是Python 2.5代碼(其替換單詞fox與鏈接<a href="/fox">fox</a> ,它避免了鏈接內的替換):

import re

content="""
<div>
    <p>The quick brown <a href='http://en.wikipedia.org/wiki/Fox'>fox</a> jumped over the lazy Dog</p>
    <p>The <a href='http://en.wikipedia.org/wiki/Dog'>dog</a>, who was, in reality, not so lazy, gave chase to the fox.</p>
    <p>See &quot;Dog chase Fox&quot; image for reference:</p>
    <img src='dog_chasing_fox.jpg' title='Dog chasing fox'/>
</div>
"""

p=re.compile(r'(?!((<.*?)|(<a.*?)))(fox)(?!(([^<>]*?)>)|([^>]*?</a>))',re.IGNORECASE|re.MULTILINE)
print p.findall(content)

for match in p.finditer(content):
  print match.groups()

output=p.sub(r'<a href="/fox">\3</a>',content)
print output

輸出為:

[('', '', '', 'fox', '', '.', ''), ('', '', '', 'Fox', '', '', '')]
('', '', None, 'fox', '', '.', '')
('', '', None, 'Fox', None, None, None)

Traceback (most recent call last):
  File "C:/example.py", line 18, in <module>
    output=p.sub(r'<a href="fox">\3</a>',content)
  File "C:\Python25\lib\re.py", line 274, in filter
    return sre_parse.expand_template(template, match)
  File "C:\Python25\lib\sre_parse.py", line 793, in expand_template
    raise error, "unmatched group"
error: unmatched group
  1. 我不確定為什么反向引用\\3無法正常工作。

  2. (?!((<.*?)|(<a.*?)))(fox)(?!(([^<>]*?)>)|([^>]*?</a>))作品,請參見http://regexr.com?317bn ,這令人驚訝。 第一個負前瞻(?!((<.*?)|(<a.*?)))我感到困惑。 我認為這不起作用。 進行發現的第一場比賽, fox gave chase to the fox.</p> ,有一只<a href='http://en.wikipedia.org/wiki/Dog'>dog</a> ((<.*?)|(<a.*?)) ,並且作為否定的前瞻,它應該返回FALSE。 我不確定我是否清楚表達自己。

非常感謝!

(注意:我討厭使用BeautifulSoup。我喜歡編寫自己的正則表達式。我知道這里很多人會說正則表達式不適用於HTML處理等等。但這是一個小程序,所以我更喜歡正則表達式,而不是BeautifulSoup。)

如果您不喜歡beautifulsoup,請嘗試使用以下其他(X)HTML解析器之一:

html5lib
elementree
lxml

如果您計划或需要解析HTML(或變體),則值得學習這些工具。

我不知道為什么您的表情不起作用,我唯一注意到的是一開始的前瞻性小組,這對我來說意義不大。 這似乎很好用:

import re

content="""fox
    <a>fox</a> fox <p fox> and <tag fox bar> 
    <a>small <b>fox</b> and</a>
fox"""

rr = """
(fox)
(?! [^<>]*>)
(?!
    (.(?!<a))*
    </a
)
"""

p = re.compile(rr, re.IGNORECASE | re.MULTILINE | re.VERBOSE)
print p.sub(r'((\g<1>))', content)

暫無
暫無

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

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