[英]How to replace strings which match a regex pattern?
i have list with numbers. 我有数字清单。 I want to extract all the numbers with consecutive digits like 444,888,1111 etc.. My following python code with regex is working exactly the way I wanted.
我想提取具有连续数字的所有数字,例如444,888,1111等。我下面的带有regex的python代码正在按照我想要的方式工作。
import re
numbers = ['44444', '123', '444', '454', '76587', '888', '9090', '1111', '321', '4321', '4563', '3333', '543', '765', '4567', '555', '99999', '11211','11']
conList = []
for num in numbers:
if re.search(r'^(\d)\1+$',num):
conList.append(num)
print('conList :',conList)
Result: 结果:
conList : ['44444', '444', '888', '1111', '3333', '555', '99999', '11']
Now I am trying to achieve the same result without using a regex pattern. 现在,我尝试不使用正则表达式模式来达到相同的结果。 How can I replace that regex pattern with some python code?
如何用某些python代码替换该正则表达式模式? (I am trying this only for educational purpose. I will post my answer if I got one.)
(我仅出于教育目的尝试此操作。如果得到答案,我将发布答案。)
This is my attempt to solve this problem.
这是我解决这个问题的尝试。
for num in numbers:
if len(set(num)) == 1 and len(num) >1:
conList.append(num)
print('conList :',conList)
Or, using list comprehension 或者,使用列表理解
conList = [ num for num in numbers if len(num) > 1 and len(set(num)) == 1 ]
print('conList : %s', conList)
Or, using filter 或者,使用过滤器
conList = filter(lambda x: len(x) > 1 and len(set(x)) == 1, numbers)
使用pythonic和快速的列表理解方法:
[i for i in numbers if len(set(i)) == 1]
You can do this in one line using list comprehensions as the following: 您可以使用列表推导功能如下一行完成此操作:
numbers = ['44444', '123', '444', '454', '76587', '888', '9090', '1111', '321', '4321', '4563', '3333', '543', '765', '4567',
'555', '99999', '11211', '11']
conList = [x for x in numbers if x.count(x[0]) == len(x)]
print conList
output: 输出:
['44444', '444', '888', '1111', '3333', '555', '99999', '11']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.