【发布时间】:2011-01-27 12:37:40
【问题描述】:
我正在尝试用href="../directory/index.html" 替换所有href="../directory" 实例。
在 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>
EDIT:重复的'index.html'实际上是多次匹配的结果。 (例如 href="../personal-autonomy/index.htmlindex.htmlindex.htmlindex.html" 是因为 ../personal-autonomy 在原始源中被找到了四次)。
作为一个一般的正则表达式问题,如何在不向所有匹配项添加额外的“index.html”的情况下替换所有实例?
【问题讨论】:
-
你能告诉我们输入是什么吗?
-
您为什么要尝试使用正则表达式解析 HTML?有很多强大的解析器可以通过读取 DOM 轻松提取这些语句。正则表达式不是为 HTML 设计的。
-
一种解决方案:在源 HTML 上运行 .splitlines(),然后在每一行上运行正则表达式,产生了所需的结果。但是,我仍然不确定为什么不拆分就无法工作。