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正则表达式中工作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”