Python Regex UTF8语法

2024-09-28 05:18:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直在努力清理一些文字。但在regex上被卡住了,最后re.sub公司。但最终导致语法错误。 原始代码:

名称清理测试

import re

input = u'CHEZ MADU 東久留米店(シェマディ)【東京都東久留米市】'

pattern = re.compile(ur'(【(.*?)\】)', re.UNICODE)\

print(re.sub(input, pattern, ''))

给我这个错误:

^{pr2}$

我一直在测试另一个regex线程的代码:python regular expression with utf8 issue

它给出了同样的错误。问题的根源是什么?在


Tags: 代码importre名称input错误公司regex
2条回答

如果你不使用原始字符串表示法,对我来说效果很好。另外,我认为您没有正确使用re.sub

re.sub(pattern, repl, string, count=0, flags=0)

这并没有给我带来错误:

import re
input = u'CHEZ MADU 東久留米店(シェマディ)【東京都東久留米市】'
pattern = re.compile(u'(【(.*?)\】)', re.UNICODE)
print(re.sub(pattern, '', input))

这适用于Python2和3,但不需要在3上使用unicode说明符。在

ur'....'语法自python3.3以来无效(请参见http://bugs.python.org/issue15096

有点奇怪的是,语法错误是在字符串的末尾。。。在

>>> ru'my string'
  File "<stdin>", line 1
    ru'my string'
                ^
SyntaxError: invalid syntax

因此,在Python 3中,可以使用:

  • 'my string'u'mystring',意思相同(后者在python3.3中重新引入,以与python2代码兼容,请参见PEP 414
  • r'my string with \backslashes'表示“原始”字符串。在

相关问题 更多 >

    热门问题