【发布时间】:2016-06-21 11:59:34
【问题描述】:
我有一个类似的字符串:
"<p>
<style type=""text/css"">
P { margin-bottom: 0.08in; direction: ltr; widows: 2; orphans: 2; }A:link { color: rgb(0, 0, 255); } </style>
</p>
<p style=""font-variant: normal; font-style: normal; font-weight: normal"">
<font face=""Trebuchet MS, Arial, Verdana, sans-serif""><span style=""font-size: 12px; background-color: rgb(238, 238, 238);"">blablabla. </span></font></p>
<p style=""font-variant: normal; font-style: normal; font-weight: normal"">
<font face=""Trebuchet MS, Arial, Verdana, sans-serif""><span style=""font-size: 12px; background-color: rgb(238, 238, 238);"">tjatjatja</span></font><span style=""font-family: 'Trebuchet MS', Arial, Verdana, sans-serif; font-size: 12px; background-color: rgb(238, 238, 238);"">tjetjetje</span><span style=""font-size: 12px; font-family: 'Trebuchet MS', Arial, Verdana, sans-serif; background-color: rgb(238, 238, 238);"">.</span></p>
<p style=""font-variant: normal; font-style: normal; font-weight: normal"">
<span style=""font-family: 'Trebuchet MS', Arial, Verdana, sans-serif; font-size: 12px; background-color: rgb(238, 238, 238);"">huehuehue</span></p>
"
我想删除第一个样式标签及其内容。我有一个像这样的正则表达式:
([\s\S]*)<style type=""text\/css"">[\s\S]+<\/style>([\s\S]*)
它只匹配第一个样式标签,但是当我尝试在 python 中删除它时:
re.sub(r'([\s\S]*)<style type=""text/css"">[\s\S]*</style>([\s\S]*)', r'\1\2', cell_text, flags=re.M)
它不起作用。我认为这要么与组有关,要么与多行字符串有关。有什么想法吗?
【问题讨论】:
-
您至少必须使
[\s\S]*非贪婪([\s\S]*?),以防更多style标签是可能的。 -
而且...我不是 python 专家,但你的正则表达式有单引号 - 为什么 2
"在里面?我猜这个字符串有 2,因为这就是你在 python 中转义引号的方式,但在单引号字符串中不应该是必需的,或者......? -
不确定示例数据为何包含引号。为了解决这个问题,我对包含正则表达式的原始字符串使用了单引号。
标签: regex python-3.x web-scraping