【问题标题】:How to find a string that is (and isn't) wrapped around some pattern in Python?如何在 Python 中找到一个包含(和不包含)某个模式的字符串?
【发布时间】:2019-07-25 04:18:08
【问题描述】:

假设我有以下字符串(是的,它是字符串格式)。

body = 'start [caption] <a>A Images</a> [/caption] <a> Another Image </a> end'
  • 案例 1,当我发现 &lt;a&gt;[caption] [/caption] 包围时,我想做某事并
  • 案例 2,当我发现 &lt;a&gt; 没有[caption] [/caption] 包裹时,我想做一些事情其他

我已经可以通过以下方式完成第一个:

captionPattern = r'\[caption.*?/caption\]'

现在,我也想做同样的事情,但要提取未被[caption] [/caption] 包裹的&lt;a&gt;

我可以编写代码来简单地匹配&lt;a&gt;...&lt;/a&gt;,但这将匹配所有&lt;a&gt;...&lt;/a&gt;,包括案例1中的那些。

【问题讨论】:

  • 尝试查看beautifulsoup
  • 如果存在,[caption] 是否总是紧挨着&lt;a&gt; 标签?
  • @Akaisteph7,是的,像这样[caption id="attachment_12345" align="aligncenter" width="123"]&lt;a href=...
  • @MdShihabJamil 抱歉回答迟了。见下文。

标签: regex python-3.x tags


【解决方案1】:

你可以这样做:

body = 'start [caption] <a>A Images</a> [/caption] <a> Another Image </a> end'
captionPattern = "(\[caption.*?/caption\])|(<a>.*?</a>)"
results = re.findall(captionPattern, body)

with_caption = [elem for elem in results[0] if elem]
without_caption = [elem for elem in results[1] if elem]
print(with_caption)
print(without_caption)

输出:

['[caption] <a>A Images</a> [/caption]']
['<a> Another Image </a>']

【讨论】:

    猜你喜欢
    • 2014-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-25
    • 1970-01-01
    • 2012-11-21
    • 1970-01-01
    相关资源
    最近更新 更多