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

Unicode re.sub()不适用于\g<0>(组0)

  •  3
  • alvas  · 技术社区  · 11 年前

    为什么 \g<0> 使用unicode正则表达式?

    当我尝试使用 \g<0> 要使用普通字符串regex在组前后插入空格,它的工作原理是:

    >>> punct = """,.:;!@#$%^&*(){}{}|\/?><"'"""
    >>> rx = re.compile('[%s]' % re.escape(punct))
    >>> text = '''"anständig"'''
    >>> rx.sub(r" \g<0> ",text)
    ' " anst\xc3\xa4ndig " '
    >>> print rx.sub(r" \g<0> ",text)
     " anständig " 
    

    但使用unicode regex时,不会添加空格:

    >>> punct = u""",–−—’‘‚”“‟„!£"%$'&)(+*-€/.±°´·¸;:=<?>@§#¡•[˚]»_^`≤…\«¿¨{}|"""
    >>> rx = re.compile("["+"".join(punct)+"]", re.UNICODE)
    >>> text = """„anständig“"""
    >>> rx.sub(ur" \g<0> ", text)
    '\xe2\x80\x9eanst\xc3\xa4ndig\xe2\x80\x9c'
    >>> print rx.sub(ur" \g<0> ", text)
    „anständig“
    
    1. 我该怎么办 \g 使用unicode正则表达式?
    2. 如果(1)不可能,如何让unicode regex输入中字符前后的空格 punct ?
    1 回复  |  直到 8 年前
        1
  •  1
  •   moliware    11 年前

    我认为你有两个错误。首先,你不能逃避 punct 就像第一个例子一样 re.escape 你有这样的角色 [] 需要逃离。第二, text 变量不是unicode。有效的示例:

    >>> punct = re.escape(u""",–−—’‘‚”“‟„!£"%$'&)(+*-€/.±°´·¸;:=<?>@§#¡•[˚]»_^`≤…\«¿¨{}|""")
    >>> rx = re.compile("["+"".join(punct)+"]", re.UNICODE)
    >>> text = u"""„anständig“"""
    >>> print rx.sub(ur" \g<0> ", text)
     „ anständig “