我正在将wordpress博客迁移到Jekyll的过程中遇到以下障碍:
我想分析文本,如
[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]
所以我恢复了标题标签之间的所有文本,即
[![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代码:
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 Domain
任何帮助都将不胜感激!谢谢。你知道吗
主要问题是
match.groups()[0]
,而您应该访问match.group(1)
,因为您用模式中的一对无转义括号捕获了所需的部分,并且它们是唯一一对捕获括号,因此ID=1。你知道吗.*
一起使用,同时需要.*?
尽可能少地匹配除换行符以外的字符注意:如果文本跨越多行,还应该将} ,以便
re.DOTALL
或re.S
传递给^{.
可以匹配换行符。你知道吗参见regex demo和Python demo:
打印:
相关问题 更多 >
编程相关推荐