【问题标题】:Regular Expression r.match on search in list正则表达式 r.match 在列表中搜索
【发布时间】:2021-07-15 06:06:47
【问题描述】:

Regular Expressions: Search in list

filter(r.match, list)

这个帖子里有r.match,r.match是什么。

我的理解是r 代表 re.compile() 并返回一个模式。但是深入https://docs.python.org/3/library/re.html#re.compile,只有 Pattern.match() 方法吗?没有模式。匹配..

【问题讨论】:

    标签: python python-3.x regex


    【解决方案1】:

    r是变量,是一个模式。

    正如您在第二个答案中看到的那样,它被分配给:

    r = re.compile(".*cat")
    

    之所以没有括号是因为它使用了filter函数自动添加括号并将列表中的元素添加到过滤器中。

    docs中提到的:

    从函数返回 true 的那些可迭代元素构造一个迭代器。 iterable 可以是序列、支持迭代的容器或迭代器。如果function为None,则假定恒等函数,即iterable中所有为false的元素都被移除。

    注意 filter(function, iterable) 等价于生成器表达式 (item for item in iterable if function(item)) if function is not None and (item for item in iterable if item) if function is None.

    如您所见,它与带括号的生成器相同。 filter 函数不需要括号,这是它的特色。

    【讨论】:

      【解决方案2】:

      不,r 是代码前面的编译模式。类似的东西

      import re
      r = re.compile(r'hello')
      

      【讨论】:

      • 他也在问为什么re.match后面没有括号。哈哈
      猜你喜欢
      • 2011-04-08
      • 2021-02-09
      • 2013-11-02
      • 1970-01-01
      • 1970-01-01
      • 2010-09-23
      • 1970-01-01
      • 2014-06-06
      • 2014-06-02
      相关资源
      最近更新 更多