我有类似的文本
-
我只是想从
p
标签中提取内容 -
我不想消除
<p>
或它们之间的任何其他标签
d = "<p><p>{'Area': 'Square',</p>n<p> <tr> <td>'Flag': 'com'}</p></p>"
我的代码低于
import re
re.sub('<[^<>]+>', '',d)
我的输出是
"{'Area': 'Square',nxa0xa0'Flag': 'com'}"
预期输出仅替换第一个p
和最后一个p
标签
"<p>{'Area': 'Square',</p>n<p> <tr> <td>'Flag': 'com'}</p>"
使用
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