简体   繁体   中英

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

From this list problems= ["32 + 698", "3801 - 2", "45 + 43", "123 + 49"]

I want to get these numbers "\d*\s" that means 32,3801,45,123

Is there a way to look in each item of list and search there with a list comprehension?

I have only this attempt print([x for x in problems if re.search(r'\d*\s',x)]) , but it prints whole item if the "\d*\s" is there, so I get again ["32 + 698", "3801 - 2", "45 + 43", "123 + 49"]

(My aim is have a lenght of the longer number of each item, that would be 3,4,2,3)

You need to extract the first part before space in your strings. This can be done using group capturing. Here is the code you can use:

[re.search('(\d+)\s', x).group(1) for x in problems if re.search(r'(\d)*\s',x)]

Here (\d+)\s matches for one or more digits before a whitespace character and we extract the first group using the group(1) method.

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