【问题标题】:How do I remove all strings containing digits before "hs" like "18hs" from a list of strings? [closed]如何从字符串列表中删除所有包含“hs”之前的数字的字符串,例如“18hs”? [关闭]
【发布时间】:2019-07-13 11:57:30
【问题描述】:

我有一个字符串列表,例如:

["hello","18hs","18aaa","21hr"]

如何删除与任何数字加上"hs""h""hr" 匹配的所有字符串?

注意:我不想丢失任何以“h”结尾的字符串,比如“fish”。

所需输出:["hello,"18aaa"]

我知道可以通过正则表达式完成,但我无法正确设置捕获组。

【问题讨论】:

    标签: python regex string substring


    【解决方案1】:
    >>> import re
    >>> words = ["hello", "18hs", "18aaa", "21hr"]
    >>> [w for w in words if not re.match(r'\d+h', w)]
    ['hello', '18aaa']
    

    这会遍历列表并保留与正则表达式 \d+h 不匹配的项目,这意味着“一个或多个数字后跟一个 h”。

    如果您需要保留7hg 之类的字符串,请使用更具体的正则表达式\d+h(s|r)?$,这意味着“一个或多个数字,h,可选的s 或r,字符串的结尾”:

    >>> words = ["hello", "18hs", "18aaa", "21hr", '7hg']
    >>> [w for w in words if not re.match(r'\d+h(s|r)?$', w)]
    ['hello', '18aaa', '7hg']
    

    还要注意re.match 自动匹配字符串的开头,所以它就像一个隐含的^ 在正则表达式的开头。

    【讨论】:

    • 谢谢!这就是我要找的。我是个新手……
    • 根据要求,正则表达式应为^\d+h(s|r)?$
    • @Flinsch 好点,虽然要求很模糊。我已经添加了。
    【解决方案2】:
    • 遍历它们
    • 检查此正则表达式是否有任何匹配项:(\d+h)
    • 如果是,删除元素
    • 否则不要

    很简单的东西。

    【讨论】:

    • 模式[hr|h|hs] 将匹配hrs| 集合中的一个字符。此外,\d+ 周围的括号没有任何作用。
    • 正则表达式可以简化为\d+h
    • 你们都说对了,我会调整答案-谢谢。
    【解决方案3】:

    如果你像这样使用列表过滤器 + lambdas 应该很简单:

    my_list = ["hello","18hs","18aaa","21hr"] # input data
    
    custom_filters = [lambda x: not x.endswith('hr'),  
                      lambda x: not x.endswith('hs'), 
                      lambda x: not x.endswith('h')] # define custom filters
    
    final = list(filter(lambda x: all([custom_filter(x) for custom_filter in custom_filters]), my_list)) # apply custom filters one by one
    
    # should result in ["hello", "18aaa"]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-01-26
      • 1970-01-01
      • 1970-01-01
      • 2021-05-30
      • 1970-01-01
      • 2023-02-06
      • 1970-01-01
      相关资源
      最近更新 更多