python - 正则表达式匹配中的变音符号(通过语言环境?)

标签 python regex locale

令我惊讶的是我无法在正则表达式中匹配德语变音符号。我尝试了几种方法,大多数涉及设置语言环境,但到目前为止都无济于事。

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/

相关文章:

java - 查找为给定语言环境设置的 UnicodeBlock

c++ - 如何使用 boost locale 检查时区是否存在

python - Django:从根目录开始的多个 url 模式分布在文件中

javascript - 使用 RegExp 匹配多个实例并存储值 (JavaScript)

sql-server - 源列 '0' 的区域设置 ID 'PAT_NUM_ADT' 与目标列 '1033' 的区域设置 ID 'PAT_ID_OLD' 不匹配

r - 查找连续匹配的模式索引

php - 正则表达式匹配重叠/交叉

python - 用另一个列表中的项目替换列表中的项目

python - py.test conftest - 根据 sys.argv 修改 fixture 参数

python - numpy.dstack 用于 3D 数组?