简体   繁体   中英

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:

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.

>>> 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. [xX] matches both upper and lowercase 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']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM