regexp匹配中的元音变音符(通过locale?)

2024-05-16 11:51:02 发布

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

我很惊讶我不能在regexp中匹配德语元音变音。我尝试了几种方法,大多数都是设置区域设置,但到目前为止都没有效果。

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+正确匹配的umlaut-u(ü)。同时删除re.L标志或在模式字符串前面加上u(使其成为unicode)也没有帮助我。

有什么想法吗?如何正确使用标志re.L


Tags: 方法re区域标志defjkllocalelc
2条回答

在我的例子中,\S\w给出了更好的结果,加上将文件保存为utf-8,再加上使用re.UNICODE

您是否尝试使用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.

相关问题 更多 >