【发布时间】: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