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

我有一个看起来像这样的字符串列表,


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/22

list/category/22561

list/category/0027


我使用了以下代码:


newlist = []

for i in strlist:

    if re.match('list/category/[0-9]+[0-9]',i):

        newlist.append(i)

        print(i)

但这是我的输出:


list/category/22

list/category/22561

list/category/3361b

list/category/22?=1512

list/category/216?=591jf1!

list/category/91121/91251

list/category/0027

如何修复我的正则表达式?还有一种方法可以使用过滤器或匹配命令而不是 for 循环在一行中执行此操作吗?


慕桂英546537
浏览 171回答 1
1回答

catspeake

您可以尝试以下正则表达式:^list\/category\/\d+$上述正则表达式的解释:^- 表示给定测试字符串的开始。\d+- 匹配出现一次或多次的数字。$ - 匹配测试字符串的结尾。这是您的正则表达式遗漏的部分。上述正则表达式的演示在这里。Python 中的实现import repattern = 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)您可以在此处找到上述实施的示例运行。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python