[英]Find a specific pattern (regular expression) in a list of strings (Python)
So I have this list of strings: 所以我有这个字符串列表:
teststr = ['1 FirstString', '2x Sec String', '3rd String', 'x forString', '5X fifth']
What I need to do, is to get all the elements from this list that contain: 我需要做的是从这个列表中获取包含以下内容的所有元素:
number + "x"
or 要么
number + "X"
For example if I have the function 例如,如果我有这个功能
def SomeFunc(string):
#do something
I would like to get an output like this: 我想得到这样的输出:
2x Sec String
5X fifth
I found somewhere here in StackOverflow this function: 我在StackOverflow中找到了这个函数:
def CheckIfContainsNumber(inputString):
return any(char.isdigit() for char in inputString)
But this returns each string that has a number. 但是这将返回每个具有数字的字符串。
How can I expand the functions to get the desired output? 如何扩展功能以获得所需的输出?
Use re.search
function along with the list comprehension. 使用re.search
函数和列表re.search
。
>>> teststr = ['1 FirstString', '2x Sec String', '3rd String', 'x forString', '5X fifth']
>>> [i for i in teststr if re.search(r'\d+[xX]', i) ]
['2x Sec String', '5X fifth']
\\d+
matches one or more digits. \\d+
匹配一个或多个数字。 [xX]
matches both upper and lowercase x
. [xX]
匹配大写和小写x
。
By defining it as a separate function. 通过将其定义为单独的功能。
>>> def SomeFunc(s):
return [i for i in s if re.search(r'\d+[xX]', i)]
>>> print(SomeFunc(['1 FirstString', '2x Sec String', '3rd String', 'x forString', '5X fifth']))
['2x Sec String', '5X fifth']
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.