【问题标题】:Regular expression to filter list of strings matching a patternPython正则表达式过滤匹配模式的字符串列表
【发布时间】:2013-03-02 10:23:35
【问题描述】:

我更多地使用 R,而且我在 R 中更容易做到这一点:

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

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

附:我正在使用谷歌的 python 练习来学习 python。而且我更喜欢使用回归表达式。

【问题讨论】:

    标签: python regex list subset


    【解决方案1】:

    一般来说,你可以使用

    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']
    

    或者,反转结果并获取所有与正则表达式不匹配的项目:

    list(filter(lambda x: not reg.search(x), test))
    # >>> ['bbb', 'ccc', 'axx']
    

    请参阅Python demo

    使用说明

    • re.search 在字符串中找到第一个正则表达式匹配 anywhere 并返回一个匹配对象,否则 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

    【讨论】:

      【解决方案2】:

      您可以使用以下内容来查找列表中是否有任何字符串以'x'开头

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

      【讨论】:

      • 我想提取以“x”开头的字符串,但我看不到你的答案可以给出我期望的输出。
      • 我可以在re库中使用re.match或者类似的函数吗?
      • @lok​​heart 您绝对可以在上面的列表理解中使用re.match 代替starswith
      • @squiguy 试过 [x for x in test if re.match("^x",x)] 并且它有效
      • @lok​​heart 酷:)。玩得开心!
      【解决方案3】:

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

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

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

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

      【讨论】:

        【解决方案4】:

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

        输入:

        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')]]
        

        【讨论】:

          【解决方案5】:

          这是一些很好的即兴创作。可能有帮助..

          import re
          l= ['bbb', 'ccc', 'axx', 'xzz', 'xaa'] #list
          s= str( " ".join(l))                   #flattening list to string
          re.findall('\\bx\\S*', s)               #regex to find string starting with x
          
          ['xzz', 'xaa']
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2020-11-29
            • 2011-11-28
            • 2015-11-14
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多