Find a specific pattern (regular expression) in a list of strings (Python)

So, I have this list of lines:

teststr = ['1 FirstString', '2x Sec String', '3rd String', 'x forString', '5X fifth']

What I need to do is get all the items from this list that contain:

number + "x" 

or

number + "X"

For example, if I have a function

def SomeFunc(string):
    #do something

I would like to get this output:

2x Sec String
5X fifth

I found this function somewhere here in StackOverflow:

def CheckIfContainsNumber(inputString):
    return any(char.isdigit() for char in inputString)

But this returns every line with a number.

How can I expand the functions to get the desired result?

+4
source share
1 answer

Use the function re.searchalong with the list.

>>> 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 upper and lower case x.

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']
+6
source

All Articles