【问题标题】:Use regular expression to remove contents in brackets in python在python中使用正则表达式删除括号中的内容
【发布时间】:2014-05-23 15:49:24
【问题描述】:

我有一个list

['14147618', '(100%)', '6137776', '(43%)', '5943229', '(42%)', '2066613', '(14%)', 'TOTAL']

也可以作为字符串'14147618 (100%) 6137776 (43%) 5943229 (42%) 2066613 (14%) TOTAL\n'

使用正则表达式,我如何返回:

['14147618', '6137776, '5943229', 2066613']

【问题讨论】:

    标签: python regex list python-2.7


    【解决方案1】:

    你根本不需要 RegEx,你可以简单地过滤掉只有数字的数据,用这个列表理解

    print [item for item in data if item.isdigit()]
    # ['14147618', '6137776', '5943229', '2066613']
    

    或者你也可以使用filter内置函数,像这样

    print filter(str.isdigit, data)
    # ['14147618', '6137776', '5943229', '2066613']
    

    编辑:如果您将整个数据作为单个字符串,您可以根据空格字符拆分数据,然后使用相同的逻辑

    data = '14147618 (100%)   6137776 (43%)   5943229 (42%)   2066613 (14%)  TOTAL\n'
    print [item for item in data.split() if item.isdigit()]
    # ['14147618', '6137776', '5943229', '2066613']
    print filter(str.isdigit, data.split())
    # ['14147618', '6137776', '5943229', '2066613']
    

    【讨论】:

    • 你能告诉我如果a = '14147618 (100%) 6137776 (43%) 5943229 (42%) 2066613 (14%) TOTAL\n' 我如何得到['14147618', '6137776, '5943229', 2066613']
    • @VeilEclipse 您可以使用与a.split()相同的程序
    【解决方案2】:

    正如@thefourtheye 所说,完全没有必要使用正则表达式,但如果你真的想使用正则表达式,你可以使用:

    import re
    
    a = ['14147618', '(100%)', '6137776', '(43%)', '5943229', '(42%)', '2066613', '(14%)', 'TOTAL']
    result = []
    
    for e in a:
        m = re.match(r'\d+', e)
        if m is not None:
            result.append(e)
    
    print result
    # ['14147618', '6137776', '5943229', '2066613']
    

    注意:这也可以写成列表推导:

    print [e for e in a if re.match(r'\d+', e)]
    

    【讨论】:

      【解决方案3】:

      这是一种方法:

      >>> l = ['14147618', '(100%)', '6137776', '(43%)', '5943229', '(42%)', '2066613', '(14%)', 'TOTAL']
      >>> [el for el in l if re.match(r'\d+$', el)]
      ['14147618', '6137776', '5943229', '2066613']
      

      【讨论】:

        【解决方案4】:

        使用re模块:

        >>> import re
        >>> [item for item in s if re.match(r'\d+',item)]
        ['14147618', '6137776', '5943229', '2066613']
        

        【讨论】:

          【解决方案5】:

          完全不需要使用re模块,你可以使用filterover list

          试试这个,

          >>> a=['14147618', '(100%)', '6137776', '(43%)', '5943229', '(42%)', '2066613', '(14%)', 'TOTAL']
          >>> filter(str.isdigit, a)
          ['14147618', '6137776', '5943229', '2066613']
          >>>
          

          【讨论】:

            【解决方案6】:

            或者如果你想要除最后一个之外的偶数索引元素:

            print [data[i] for i in range(0,len(data)-1,2)]
            

            【讨论】:

              猜你喜欢
              • 2023-02-11
              • 2020-08-04
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2010-10-05
              • 1970-01-01
              • 1970-01-01
              相关资源
              最近更新 更多