【问题标题】:Unicode re.sub() doesn't work with \g<0> (group 0)Unicode re.sub() 不适用于 \g<0> (组 0)
【发布时间】:2013-10-17 13:04:27
【问题描述】:

为什么 \g&lt;0&gt; 不能与 unicode 正则表达式一起使用?

当我尝试使用\g&lt;0&gt; 在具有普通字符串正则表达式的组之前和之后插入一个空格时,它可以工作:

>>> 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 正则表达式,不会添加空格:

>>> 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 正则表达式输入punct 中字符前后的空格?

【问题讨论】:

    标签: python regex string unicode regex-group


    【解决方案1】:

    我认为你有两个错误。首先,您不会像第一个示例中的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 “
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-22
      • 2020-09-06
      • 1970-01-01
      • 2016-06-27
      相关资源
      最近更新 更多