我正在将 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.DOTALL
或 re.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/