首页 > 解决方案 > 使用 re.search 在 python 中找不到特定的子字符串

问题描述

我想在这里静音“name_list”并扫描列表中的每个字符串以查找“nametosearch”中的术语列表。对于每个带有“$”符号的术语,代码应从“name_list”中删除该特定字符串。

相反,我的代码适用于“$placeholder”,但根本不适用于“$hidden”。

当一切都完成后,我只想要

<input class="form-control" maxlength="20" name="auth_user_name" size="28" type="text" value=""/>

留下来,相反我得到:

   <input name="ib_s" size="64" type="hidden" value="e44b06a472945566fca51723110ab34a">new user?', '<input class="form-control" maxlength="20" name="auth_user_name" size="28" type="text" value=""/>

我哪里错了?(代码贴在下面)

import re

name_list=['<input class="form-control" name="keywords" placeholder="enter search term, ad #, or username" type="text" value="">', '<input name="ib_s" size="64" type="hidden" value="e44b06a472945566fca51723110ab34a">new user?', '<input class="form-control" maxlength="20" name="auth_user_name" size="28" type="text" value=""/>']

nametosearch=('user', '$placeholder', '$hidden') 


for x3 in name_list:
   for z2 in nametosearch:
      if z2[0]=='$' and re.search(z2[1:],x3):
         name_list.remove(x3)

很高兴提供更多详细信息,我真的不知道您可能还需要什么,但请询问。

编辑:'nametosearch' 是一个元组,因为内容是函数的参数。

谢谢

标签: python

解决方案


import re
name_list=['<input class="form-control" name="keywords" placeholder="enter search term, ad #, or username" type="text" value="">', '<input name="ib_s" size="64" type="hidden" value="e44b06a472945566fca51723110ab34a">new user?', '<input class="form-control" maxlength="20" name="auth_user_name" size="28" type="text" value=""/>']

nametosearch=('user', '$placeholder', '$hidden') 
index_to_remove=[]

for x3,i in zip(name_list,range(len(name_list))):
        for z2 in nametosearch:
            if z2[0]=='$' and re.search(z2[1:],x3):
                index_to_remove.append(i)

newlist= [i for j, i in enumerate(name_list) if j not in index_to_remove]
print(newlist)

输出:

['<input class="form-control" maxlength="20" name="auth_user_name" size="28" type="text" value=""/>']

推荐阅读