代码之家  ›  专栏  ›  技术社区  ›  normanius

Python one liner能够稳健地提取正则表达式搜索的结果

  •  0
  • normanius  · 技术社区  · 9 年前

    def search(x):
       # Return a keyword or None if not found.
       ret = re.search('^(foo|bar|baz)', x)
       return ret.group() if ret else None
    
    texts = ['fool', 'minibar', 'bark', 'honk']
    map(search, texts)
    

    ['foo', None, 'bar', None]

    我想用一个单行程序编写它,而不必声明单独的函数。做 re 或者其他模块提供了一种更直接的方法来查找和检索匹配项,基本上是我的上述功能的捷径?例如,是否存在以下情况?

    texts = ['fool', 'minibar', 'honk']
    map(lambda x: re.search_and_retrieve, texts)
    

    或者有没有一种简洁易读的方法来测试和安全地检索 re.search()

    5 回复  |  直到 9 年前
        1
  •  3
  •   9000    9 年前

    这是可能的,但你不想这样:

    (lambda txt: (lambda x: x.group() if x else None)(re.search('foo', txt)))
    

    None Maybe 或 Option ,如果函数存在,则无法将其简洁地链接到值。(如果你想念这些家伙,看看扩展Python的椰子语言。)

        2
  •  3
  •   Kevin    9 年前

    这显然有点老套,但为了完整性起见,这里有一个替代现有答案的方法,不需要连续嵌套lambda或多次调用正则表达式引擎:

    >>> map(lambda x: getattr(re.search('^(foo|bar|baz)', x), "group", lambda: None)(), texts)
    ['foo', None, 'bar', None]
    

    getattr(expression, method_name, lambda: None)() 近似等于 expression.method_name() if expression else None 除了你不需要写 expression 两次我认为这不是一个好的实践——标识符应该是标识符,而不是字符串文字——但在非生产质量代码中,这是一个有趣的概念。

        3
  •  0
  •   zipa    9 年前

    [re.findall('^(foo|bar|baz)', i)[0] if re.search('^(foo|bar|baz)', i) else None for i in texts]
    
        4
  •  0
  •   Ajax1234    9 年前

    你可以用 filter

    texts = ['fool', 'minibar', 'honk']
    final_val = list(filter(lambda x:x is not None, map(lambda x: re.search('^(foo|bar|baz)', x).group(0) if re.search('^(foo|bar|baz)', x) is not None else None, texts)))
    
        5
  •  0
  •   PramodG    9 年前

    texts = ['fool', 'minibar', 'bark', 'honk']
    
    map(lambda x : re.search('^(foo|bar|baz)', x).group() if re.search('^(foo|bar|baz)', x) else None, texts)