使用regex过滤字符串列表。

问题描述 投票:0回答:1

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

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',
]

我想使用regex来查找这个列表中的字符串,其中包含以下字符串 /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

我如何修正我的regex? 还有,有没有一种方法可以在一行中使用过滤器或匹配命令而不是for循环来完成?

python regex string list filter
1个回答
3
投票

你可以试试下面的regex。

^list\/category\/\d+$

上述regex的解释。

^ - 代表给定测试的开始 String.

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

$ - 匹配测试字符串的末端。这是你的regex遗漏的部分.

上述regex在 这里。

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)

你可以找到上述实现的示例运行。在这里。

© www.soinside.com 2019 - 2024. All rights reserved.