首页 > 解决方案 > 如何从 html 的 2 个标签中提取文本或替换第一个和最后一个标签

问题描述

我有如下文字

d = "<p><p>{'Area': 'Square',</p>\n<p> <tr> <td>'Flag': 'com'}</p></p>"

我的代码如下

import re
re.sub('<[^<>]+>', '',d)

我的输出是

"{'Area': 'Square',\n\xa0\xa0'Flag': 'com'}"

预期的只是替换第一个p和最后一个p标签

"<p>{'Area': 'Square',</p>\n<p> <tr> <td>'Flag': 'com'}</p>"

标签: pythonregex

解决方案


采用

re.sub(r'^<p>(.*)</p>$', r'\1', d, flags=re.S)

请参阅正则表达式证明

解释

--------------------------------------------------------------------------------
  ^                        the beginning of the string
--------------------------------------------------------------------------------
  <p>                      '<p>'
--------------------------------------------------------------------------------
  (                        group and capture to \1:
--------------------------------------------------------------------------------
    .*                       any character except \n (0 or more times
                             (matching the most amount possible))
--------------------------------------------------------------------------------
  )                        end of \1
--------------------------------------------------------------------------------
  </p>                     '</p>'
--------------------------------------------------------------------------------
  $                        before an optional \n, and the end of the
                           string

推荐阅读