You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python re模块移除目标代码并保留指定内容?

问题解决:移除指定代码片段并保留"remain"

正确解决方案

方法1:精准移除目标代码后清理无关内容

直接定位要删除的代码字符串,替换为空后再清理剩余杂项:

import re

keywords = '(adsbygoogle = window.adsbygoogle || []).push({}) <div class=" pirce.pdf0.92MB  carzip.tistory.com remain)'
# 移除目标广告代码片段(注意转义特殊字符)
cleantext = re.sub(r'\(adsbygoogle = window\.adsbygoogle \|\| \[\]\)\.push\(\{\}\)', '', keywords)
# 只保留"remain",删除其他所有内容
cleantext = re.sub(r'[^remain]+', '', cleantext)
print(cleantext)  # 输出:remain

方法2:直接提取目标单词(最简便)

既然目标就是保留"remain",直接匹配提取即可:

import re

keywords = '(adsbygoogle = window.adsbygoogle || []).push({}) <div class=" pirce.pdf0.92MB  carzip.tistory.com remain)'
target = re.search(r'remain', keywords)
if target:
    print(target.group())  # 输出:remain

原代码的问题分析

  1. 正则匹配逻辑错误:第三行的<ads*[^)]+>完全不对。你已经把(换成<、)换成>,此时应该用[^>]来匹配到闭合的>,而且ads*是匹配ad加任意个s,根本无法精准定位目标广告代码的开头。
  2. 冗余的括号转换:来回把括号转成尖括号再转回去,纯粹增加复杂度,完全没必要直接针对目标内容处理。
  3. 未处理末尾多余括号:原字符串最后有个多余的),经过多次转换后导致内容混乱,进一步影响结果。

内容的提问来源于stack exchange,提问作者황정학

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 00:01:38