python - 在Python中解析标题标签内的文本

标签 python regex

我正在将 WordPress 博客迁移到 Jekyll 的过程中遇到了以下障碍:

我想解析诸如

之类的文本

[caption id="attachment_1749417"align="aligncenter"width="426"][![股骨头横截面](http://www.wired.com/wp-content/uploads/2015/03/femur-head-cross-section.png)](http://www.bartleby.com/107/illus247.html) 大腿骨顶部的横截面。 ![](http://www.wired.com/wp-content/themes/Phoenix/assets/images/gallery-cam@2x.png) [格雷的解剖](http://www.bartleby.com/107/illus247.html)/公共(public)领域[/caption]

这样我就可以恢复标题标签之间的所有文本,即

[![股骨头横截面](http://www.wired.com/wp-content/uploads/2015/03/femur-head-cross-section.png)](http:///www.bartleby.com/107/illus247.html) 大腿骨顶部的横截面。 ![](http://www.wired.com/wp-content/themes/Phoenix/assets/images/gallery-cam@2x.png) [格雷的解剖](http://www.bartleby.com/107/illus247.html)/公共(public)领域

我尝试了以下Python代码:

match = re.search("\[caption.*\](.*)\[\/caption\]",caption)
if match and len(match.groups()) > 0:
    actualcaption = match.groups()[0]
    print 'actual caption: '+ actualcaption

然而,这只给了我(http://www.bartleby.com/107/illus247.html)/公共(public)领域

如有任何帮助,我们将不胜感激!谢谢。

最佳答案

主要问题是

  • 您正在访问 match.groups()[0],而您应该访问 match.group(1),因为您捕获了该部分您需要在模式中使用一对未转义的括号,并且它们是唯一一对捕获括号,因此 ID = 1。
  • 您在 .* 中使用贪婪量词,而您需要 .*? 来匹配除换行符之外的尽可能少的字符

注意:如果文本跨越多行,您还应该将 re.DOTALLre.S 传递给 re.search这样 . 可以匹配换行符。

请参阅regex demo和一个Python demo :

import re
regex = r"\[caption.*?](.*?)\[/caption]"
test_str = "[caption id=\"attachment_1749417\" align=\"aligncenter\" width=\"426\"][![femur head cross section](http://www.wired.com/wp-content/uploads/2015/03/femur-head-cross-section.png)](http://www.bartleby.com/107/illus247.html) A cross-section of the top of the thigh bone. ![](http://www.wired.com/wp-content/themes/Phoenix/assets/images/gallery-cam@2x.png) [Gray's Anatomy](http://www.bartleby.com/107/illus247.html) / Public Domain[/caption]"
match = re.search(regex, test_str)
if match:
    print(match.group(1))

打印:

[![femur head cross section](http://www.wired.com/wp-content/uploads/2015/03/femur-head-cross-section.png)](http://www.bartleby.com/107/illus247.html) A cross-section of the top of the thigh bone. ![](http://www.wired.com/wp-content/themes/Phoenix/assets/images/gallery-cam@2x.png) [Gray's Anatomy](http://www.bartleby.com/107/illus247.html) / Public Domain

关于python - 在Python中解析标题标签内的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43942896/

相关文章:

python - 删除 csv 文件中的非 ascii 字符

python - 如何在 python 中使用 selenium 将整个文本发送到文本区域而不是逐行发送?

regex - 需要使用 RegEx 防止重复字符

java - 正则表达式 "Or"返回一组Java

python - 是否有等同于 np.empty 的 tensorflow ?

python - 转换 pandas 数据框中的 tf-idf 矩阵

python - ValueError:选项名称已添加 pytest

java - 使用 Java Regex,如何检查字符串是否包含集合中的任何单词?

mysql - LIKE '[charlist]%' 语法在 MySQL 中不起作用 (phpMyAdmin)

regex - 多个捕获组 - 全部可选