【问题标题】:Filtering a list of strings using regex使用正则表达式过滤字符串列表
【发布时间】:2020-09-12 21:05:33
【问题描述】:

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

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 循环来做到这一点?

【问题讨论】:

  • 完美!可以一行完成吗?
  • 我的意思是喜欢而不是 for 循环
  • 如果你想在一行中完成,你可以使用列表推导。

标签: python regex string list filter


【解决方案1】:

你可以试试下面的正则表达式:

^list\/category\/\d+$

上述正则表达式的解释:

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

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

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

上述正则表达式在here.中的演示

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)

您可以找到上述实现的示例运行here.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-07
    • 1970-01-01
    • 2013-03-02
    相关资源
    最近更新 更多