Skip to main content
 首页 » 编程设计

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

2025年05月04日18java哥

我正在尝试替换 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”?

请您参考如下方法:

Don't parse html with regexs:

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>