[英]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"]
从这个列表中problems= ["32 + 698", "3801 - 2", "45 + 43", "123 + 49"]
I want to get these numbers "\d*\s"
that means 32,3801,45,123我想得到这些数字"\d*\s"
这意味着 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"]
我只有这个尝试print([x for x in problems if re.search(r'\d*\s',x)])
,但如果"\d*\s"
在那里,它会打印整个项目,所以我又得到["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) (我的目标是每个项目的长度更长,即 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.这里(\d+)\s
匹配空格字符之前的一个或多个数字,我们使用group(1)
方法提取第一组。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.