简体   繁体   English

在字符串列表的每个项目中查找特定模式(正则表达式)(Python)

[英]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.

相关问题 在字符串列表中查找特定模式(正则表达式)(Python) - Find a specific pattern (regular expression) in a list of strings (Python) 如何在列表中查找项目的索引,在 Python 中使用正则表达式搜索项目? - How to find an index of an item in a list, searching the item with a regular expression in Python? 用于过滤与模式匹配的字符串列表的正则表达式 - Regular expression to filter list of strings matching a pattern 在 python 中使用正则表达式替换特定模式 - replace specific pattern by using regular expression in python 用正则表达式用 python 中的字符串列表替换字符串 - Replace with regular expression a string with a list of strings in python 如何搜索列列表以找到特定的正则表达式模式,并根据该值创建新列? - How to search through a list of columns to find a specific regular expression pattern, and create a new column based on this value? 通过列表中每个成员的python正则表达式 - python regular expression through each member of a list Python - 正则表达式模式 - Python - Regular Expression pattern Python正则表达式模式 - Python Regular Expression pattern 如何在 python 中使用正则表达式忽略以特定模式开头的字符串? - How to ignore strings that start with certain pattern using regular expression in python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM