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

python正则表达式不一致

  •  2
  • hoju  · 技术社区  · 15 年前

    我根据是否预编译正则表达式得到不同的结果:

    >>> re.compile('mr', re.IGNORECASE).sub('', 'Mr Bean')
    ' Bean'
    >>> re.sub('mr', '', 'Mr Bean', re.IGNORECASE)
    'Mr Bean'
    

    这个 Python documentation 有些函数是已编译正则表达式的完整功能方法的简化版本。 但是,它还声明regexobject.sub()是 与sub()函数相同 .

    那这是怎么回事?

    4 回复  |  直到 7 年前
        1
  •  12
  •   Evan Fosmark    15 年前

    re.sub() 不能接受 re.IGNORECASE 看来是这样。

    文件规定:

    sub(pattern, repl, string, count=0)

    Return the string obtained by replacing the leftmost
    non-overlapping occurrences of the pattern in string by the
    replacement repl.  repl can be either a string or a callable;
    if a string, backslash escapes in it are processed.  If it is
    a callable, it's passed the match object and must return
    a replacement string to be used.

    然而,在其位置上使用它是可行的:

    re.sub("(?i)mr", "", "Mr Bean")
    
        2
  •  5
  •   zzzeek    15 年前

    模块级sub()调用在末尾不接受修饰符。这是“count”参数-要替换的模式出现的最大数目。

        3
  •  4
  •   miku    15 年前
    >>> help(re.sub)
      1 Help on function sub in module re:
      2 
      3 sub(pattern, repl, string, count=0)
      4     Return the string obtained by replacing the leftmost
      5     non-overlapping occurrences of the pattern in string by the
      6     replacement repl.  repl can be either a string or a callable;
      7     if a callable, it's passed the match object and must return
      8     a replacement string to be used.
    

    中没有函数参数 re.sub 对于regex标志( IGNORECASE, MULTILINE, DOTALL ) re.compile .

    选择:

    >>> re.sub("[M|m]r", "", "Mr Bean")
    ' Bean'
    
    >>> re.sub("(?i)mr", "", "Mr Bean")
    ' Bean'
    

    编辑 python 3.1增加了对regex标志的支持, http://docs.python.org/3.1/whatsnew/3.1.html . 自3.1起,如 re.sub 看起来像:

    re.sub(pattern, repl, string[, count, flags])
    
        4
  •  2
  •   Chinmay Kanchi    15 年前

    从python 2.6.4文档中:

    re.sub(pattern, repl, string[, count])
    

    re.sub()不使用标志来设置regex模式。如果需要re.ignorecase,则必须使用re.compile().sub()。