【问题标题】:regular expression in python about orpython中的正则表达式关于或
【发布时间】:2016-11-03 06:31:53
【问题描述】:

我知道p=re.compile('aaa|bbb') 可以工作,但我想使用变量重写p = re.compile('aaa|bbb'),比如

A = 'aaa'
B = 'bbb'
p = re.compile(A|B)

但这不起作用。我怎样才能重写它以便使用变量(并且它可以工作)?

【问题讨论】:

    标签: python regex python-2.7


    【解决方案1】:

    p=re.compile(A|B)

    你没有正确连接字符串。您正在做的是将"bitwise or" (the pipe) operator 应用于字符串,这当然会失败:

    >>> 'aaa' | 'bbb'
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: unsupported operand type(s) for |: 'str' and 'str'
    

    相反,您可以使用str.join()

    p = re.compile(r"|".join([A, B])) 
    

    演示:

    >>> A = 'aaa'
    >>> B = 'bbb' 
    >>> r"|".join([A, B])
    'aaa|bbb'
    

    并且,请确保您信任 AB 的来源(注意 Regex injection attacks),或/和正确的 escape 他们。

    【讨论】:

    • Python 已经提供了一个函数来转义它们,即re.escape。因此,要替换任意一组文字字符串,您只需执行以下操作:r'|'.join(map(re.escape, literals_to_alternate_on)).
    猜你喜欢
    • 2012-01-26
    • 2017-11-13
    • 1970-01-01
    • 2013-12-25
    • 2018-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-26
    相关资源
    最近更新 更多