使用正则表达式在python中的子集列表

时间:2013-03-14 06:57:10

标签: python regex subset

我使用R更多,我在R中更容易做到:

> test <- c('bbb', 'ccc', 'axx', 'xzz', 'xaa')
> test[grepl("^x",test)]
[1] "xzz" "xaa"

但如果test是一个列表,怎么在python中做呢?

P.S。我正在使用谷歌的python练习学习python。我更喜欢使用回归表达式。

5 个答案:

答案 0 :(得分:1)

您可以使用filter。我假设您想要一个包含旧元素的新列表。

new_test = filter(lambda x: x.startswith('x'), test)

或者,如果要在过滤器函数中使用正则表达式,可以尝试以下操作。 它需要导入re模块。

new_test = filter(lambda s: re.match("^x", s), test)

答案 1 :(得分:1)

当您想从列表中的每个字符串中提取多个数据点时的示例:

输入:

2021-02-08 20:43:16 [debug] : [RequestsDispatcher@_execute_request] Requesting: https://test.com&uuid=1623\n

代码:

pat = '(.* \d\d:\d\d:\d\d) .*_execute_request\] (.*?):.*uuid=(.*?)[\.\n]'
new_list = [re.findall(pat,s) for s in my_list]

输出:

[[('2021-02-08 20:43:15', 'Requesting', '1623')]]

答案 2 :(得分:0)

您可以使用以下命令查找列表中的任何字符串是否以'x'

开头
>>> [e for e in test if e.startswith('x')]
['xzz', 'xaa']
>>> any(e.startswith('x') for e in test)
True

答案 3 :(得分:0)

通常,您可以使用

import re                                  # Add the re import declaration to use regex
test = ['bbb', 'ccc', 'axx', 'xzz', 'xaa'] # Define a test list
reg = re.compile(r'^x')                    # Compile the regex
test = list(filter(reg.search, test))      # Create iterator using filter, cast to list 
# => ['xzz', 'xaa']

请参见Python demo

使用注意事项

  • re.search在字符串中的任意位置找到第一个正则表达式匹配项 并返回匹配对象,否则返回None
  • re.match仅在字符串开始处查找匹配项 ,不需要完全匹配的字符串。因此,re.search(r'^x', text) = re.match(r'x', text)
  • re.fullmatch仅在完整字符串与模式匹配时返回匹配项,因此re.fullmatch(r'x') = re.match(r'x\Z') = re.search(r'^x\Z')

如果您想知道r''前缀的含义,请参见Python - Should I be using string prefix r when looking for a period (full stop or .) using regex?Python regex - r prefix

答案 4 :(得分:0)

这是一些即兴作品,效果很好。可能有帮助。

{tmp}