【问题标题】:unicode string to PCRE regular expression in pythonunicode字符串到python中的PCRE正则表达式
【发布时间】:2012-10-10 22:32:30
【问题描述】:

我有一个 unicode 字符串

 u"\uC3A9\xe9" 
,我想在python中转换成PCRE支持的正则表达式
"\x{c3a9}\x{e9}​​"

是否有任何模块已经这样做了?

【问题讨论】:

    标签: python regex pcre


    【解决方案1】:

    我不知道有什么模块可以做到这一点,但这里有一个潜在的解决方案:

    import re
    
    def pcre_escape_repl(match):
        char = match.group(0)
        if ord(char) in range(32, 127):
            # if this is a printable ascii character, use re.escape instead of a \x escape
            return re.escape(char)
        # replace non-ascii (or non-printable) characters with a \x escape
        return r'\x{' + hex(ord(char))[2:] + '}'
    
    def pcre_escape(s):
        regex = re.compile('.', re.DOTALL)
        return regex.sub(pcre_escape_repl, s)
    

    例子:

    >>> print pcre_escape(u"\uC3A9\xe9")
    \x{c3a9}\x{e9}
    >>> print pcre_escape("[foo]{bar}")
    \[foo\]\{bar\}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-07
      • 2010-09-26
      • 2015-03-30
      • 2020-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-19
      相关资源
      最近更新 更多