Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 489
falco Avatar asked Feb 11 '23 10:02

falco


1 Answers

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']
like image 57
Avinash Raj Avatar answered Feb 13 '23 03:02

Avinash Raj