令我惊讶的是我无法在正则表达式中匹配德语变音符号。我尝试了几种方法,大多数涉及设置语言环境,但到目前为止都无济于事。
locale.setlocale(locale.LC_ALL, 'de_DE.UTF-8')
re.findall(r'\w+', 'abc def g\xfci jkl', re.L)
re.findall(r'\w+', 'abc def g\xc3\xbci jkl', re.L)
re.findall(r'\w+', 'abc def güi jkl', re.L)
re.findall(r'\w+', u'abc def güi jkl', re.L)
这些版本中没有一个版本能够将元音变音 (ü) 与 \w+
正确匹配。此外,删除 re.L
标志或在模式字符串前加上 u
前缀(使其成为 unicode)对我没有帮助。
有什么想法吗?如何正确使用标志 re.L
?
最佳答案
您是否尝试过使用 re.UNICODE
标志,如 doc 中所述?
>>> re.findall(r'\w+', 'abc def güi jkl', re.UNICODE)
['abc', 'def', 'g\xc3\xbci', 'jkl']
快速搜索指向这个 thread这给出了一些解释:
re.LOCALE just passes the character to the underlying C library. It really only works on bytestrings which have 1 byte per character. UTF-8 encodes codepoints outside the ASCII range to multiple bytes per codepoint, and the re module will treat each of those bytes as a separate character.
关于python - 正则表达式匹配中的变音符号(通过语言环境?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12240260/