为了账号安全,请及时绑定邮箱和手机立即绑定

使用正则表达式过滤字符串列表

使用正则表达式过滤字符串列表

慕桂英546537 2022-12-06 16:14:46
我有一个看起来像这样的字符串列表,strlist = [            'list/category/22',            'list/category/22561',            'list/category/3361b',            'list/category/22?=1512',            'list/category/216?=591jf1!',            'list/other/1671',            'list/1y9jj9/1yj32y',            'list/category/91121/91251',            'list/category/0027',]我想使用正则表达式查找此列表中的字符串,其中包含以下字符串/list/category/后跟任意长度的整数,但仅此而已,它不能包含任何字母或符号。所以在我的例子中,输出应该是这样的list/category/22list/category/22561list/category/0027我使用了以下代码:newlist = []for i in strlist:    if re.match('list/category/[0-9]+[0-9]',i):        newlist.append(i)        print(i)但这是我的输出:list/category/22list/category/22561list/category/3361blist/category/22?=1512list/category/216?=591jf1!list/category/91121/91251list/category/0027如何修复我的正则表达式?还有一种方法可以使用过滤器或匹配命令而不是 for 循环在一行中执行此操作吗?
查看完整描述

1 回答

?
catspeake

TA贡献1111条经验 获得超0个赞

您可以尝试以下正则表达式:

^list\/category\/\d+$

上述正则表达式的解释:

^- 表示给定测试字符串的开始。

\d+- 匹配出现一次或多次的数字。

$ - 匹配测试字符串的结尾。这是您的正则表达式遗漏的部分

上述正则表达式的演示在这里。

Python 中的实现

import re

pattern = re.compile(r"^list\/category\/\d+$", re.MULTILINE)

match = pattern.findall("list/category/22\n"

               "list/category/22561\n"

               "list/category/3361b\n"

               "list/category/22?=1512\n"

               "list/category/216?=591jf1!\n"

               "list/other/1671\n"

               "list/1y9jj9/1yj32y\n"

               "list/category/91121/91251\n"

               "list/category/0027") 

print (match)

您可以在此处找到上述实施的示例运行。


查看完整回答
反对 回复 2022-12-06
  • 1 回答
  • 0 关注
  • 170 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号