[英]How to extract text from 2 tags of html or replace first and last tag
我有如下文字
我只是想從p
標簽中提取內容
我不想消除<p>
或它們之間的任何其他標簽
d = "<p><p>{'Area': 'Square',</p>\n<p> <tr> <td>'Flag': 'com'}</p></p>"
我的代碼如下
import re
re.sub('<[^<>]+>', '',d)
我的 output 是
"{'Area': 'Square',\n\xa0\xa0'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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.