Python Unicode re.sub()不';无法使用\g<;0>;(第0组)

Python Unicode re.sub()不';无法使用\g<;0>;(第0组),python,regex,string,unicode,regex-group,Python,Regex,String,Unicode,Regex Group,为什么\g不能使用unicode正则表达式? 当我尝试使用\g在带有普通字符串regex的组前后插入空格时,它可以工作: >>> punct = """,.:;!@#$%^&*(){}{}|\/?><"'""" >>> rx = re.compile('[%s]' % re.escape(punct)) >>> text = '''"anständig"''' >>> rx.sub(r" \g<0&

为什么
\g
不能使用unicode正则表达式?

当我尝试使用
\g
在带有普通字符串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 " 
>>punct=“”,.:;!@$%^&*(){}{}{}}\/?>>rx=re.compile('[%s]'%re.escape(punct))
>>>文本='''anständig''
>>>rx.sub(r“\g”,文本)
““anst\xc3\xa4ndig”
>>>打印rx.sub(r“\g”,文本)
“anständig”
但使用unicode正则表达式时,不会添加空格:

>>> 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“
>punct=u”“,-−—’‘‚”“‟„!£"%$'&)(+*-€/.±°´·¸;:=@§#¡•[˚]»_^`≤…\«¿¨{}|"""
>>>rx=re.compile(“[”+”.join(punt)+“]”,re.UNICODE)
>>>text=“”anständig“
>>>rx.sub(ur“\g”,文本)
“\xe2\x80\x9eanst\xc3\xa4ndig\xe2\x80\x9c”
>>>打印rx.sub(ur“\g”,文本)
“anständig”
  • 如何使
    \g
    在unicode正则表达式中工作
  • 如果(1)不可能,如何让unicode正则表达式在
    punct
    中输入字符前后的空格

  • 我认为您有两个错误。首先,您没有像第一个示例中那样使用
    re.escape
    转义
    punct
    ,您有像
    []
    这样需要转义的字符。第二,
    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 “
    
    点击=重新转义(u“”,-−—’‘‚”“‟„!£"%$'&)(+*-€/.±°´·¸;:=@§#¡•[˚]»_^`≤…\«¿¨{}|""") >>>rx=re.compile(“[”+”.join(punt)+“]”,re.UNICODE) >>>text=u“anständig” >>>打印rx.sub(ur“\g”,文本) “anständig”