Python和re.compile返回不一致的结果

1 投票
5 回答
960 浏览
提问于 2025-04-16 10:43

我想把所有的 href="../directory" 替换成 href="../directory/index.html"

在Python中,这样做:

reg = re.compile(r'<a href="../(.*?)">')
for match in re.findall(reg, input_html):
    output_html = input_html.replace(match, match+'index.html')

会产生以下输出:

href="../personal-autonomy/index.htmlindex.htmlindex.htmlindex.html"  
href="../paternalism/index.html"  
href="../principle-beneficence/index.htmlindex.htmlindex.html"  
href="../decision-capacity/index.htmlindex.htmlindex.html" 

有没有人知道为什么第二个链接能成功替换,而其他的却不行呢?

相关的源代码部分:

<p> 

 <a href="../personal-autonomy/">autonomy: personal</a> |
 <a href="../principle-beneficence/">beneficence, principle of</a> |
 <a href="../decision-capacity/">decision-making capacity</a> |
 <a href="../legal-obligation/">legal obligation and authority</a> |
 <a href="../paternalism/">paternalism</a> |
 <a href="../identity-personal/">personal identity</a> |
 <a href="../identity-ethics/">personal identity: and ethics</a> |
 <a href="../respect/">respect</a> |
 <a href="../well-being/">well-being</a> 

</p> 

编辑: 重复出现的 'index.html' 实际上是因为匹配了多次。(比如 href="../personal-autonomy/index.htmlindex.htmlindex.htmlindex.html" 是因为 ../personal-autonomy 在原始源代码中找到了四次)。

作为一个关于正则表达式的一般性问题,如何替换所有实例而不在所有匹配中添加额外的 'index.html' 呢?

5 个回答

0

你有没有试过把前两个 . 转义一下呢?

reg = re.compile(r'<a[ ]href="[.][.]/(.*?)">')

不过我建议你使用 lxml,这样会更好。

1

我想我找到了问题所在

reg = re.compile(r'<a href="../(.*?)">')

for match in re.findall(reg, input_html):

output_html = input_html.replace(match, match+'index.html')

这里的 'input_html' 在循环里被修改了,然后又用同样的 'input_html' 去查找正则表达式,这就是错误所在 :)

5

不要用正则表达式解析HTML:

import re    
from lxml import html

def replace_link(link):
    if re.match(r"\.\./[^/]+/$", link):
        link += "index.html"
    return link

print html.rewrite_links(your_html_text, replace_link)

输出

<p> 

 <a href="../personal-autonomy/index.html">autonomy: personal</a> |
 <a href="../principle-beneficence/index.html">beneficence, principle of</a> |
 <a href="../decision-capacity/index.html">decision-making capacity</a> |
 <a href="../legal-obligation/index.html">legal obligation and authority</a> |
 <a href="../paternalism/index.html">paternalism</a> |
 <a href="../identity-personal/index.html">personal identity</a> |
 <a href="../identity-ethics/index.html">personal identity: and ethics</a> |
 <a href="../respect/index.html">respect</a> |
 <a href="../well-being/index.html">well-being</a> 

</p>

撰写回答