gpt4 book ai didi

c++ - `std::wregex` 是否支持 utf-16/unicode 或仅支持 UCS-2?

转载 作者:行者123 更新时间:2023-11-30 04:41:45 26 4
gpt4 key购买 nike

regex library被引入标准库。

在 Windows/MSVC 平台上,wchar_t 的大小为 2(16 位),wchar_t* 通常为 与系统/平台交互时(例如 CreateFileW)。

但是 std::regex 似乎不是 或者不支持它,所以我想知道 std::wregex 是否支持 或者只是

我没有在文档中找到任何关于此(Unicode 或类似)的提及。在其他语言中,发生了规范化

问题是:

std::wregex 代表 wchar_t 的大小为 2 时?

最佳答案

C++ 标准不强制对 std::string and std::wstring 进行任何编码.它们只是一系列 CharT .只有std::u8string , std::u16stringstd::u32string定义了编码

同样 std::regex and std::wregex 也环绕 std::basic_stringCharT . Their constructors接受 std::basic_string以及用于 std::basic_string 的编码也将用于 std::basic_regex .所以你说的 “std::regex 不是 utf-8 或不支持它” 是错误的。如果当前语言环境是 UTF-8 那么 std::regexstd::string将是 UTF-8(是的,现代 Windows 确实支持 UTF-8 locale )

在 Windows 上 std::wstring使用 UTF-16 所以 std::wregex也使用 UTF-16。 UCS-2 已弃用,没有人再使用它。你甚至不需要区分它们,因为 UCS-2 只是 UTF-16 的一个子集,除非你使用一些非常古老的工具来切入代理对的中间。 UTF-16 中的字符串搜索与 UCS-2 中的字符串搜索完全相同,因为 UTF-16 is self-synchronized和一个合适的针线永远不会从大海捞针中匹配。与 UTF-8 相同。如果该工具不理解 UTF-16,那么它很可能也不知道 UTF-8 是可变长度的,并且会在中间截断 UTF-8

Self-synchronization: The leading bytes and the continuation bytes do not share values (continuation bytes start with 10 while single bytes start with 0 and longer lead bytes start with 11). This means a search will not accidentally find the sequence for one character starting in the middle of another character. It also means the start of a character can be found from a random position by backing up at most 3 bytes to find the leading byte. An incorrect character will not be decoded if a stream starts mid-sequence, and a shorter sequence will never appear inside a longer one.

https://en.wikipedia.org/wiki/UTF-8#Description

您唯一需要关心的是:避免在字符中间截断,必要时在匹配前规范化字符串。如果您从不在字符类(如注释)中使用 BMP 之外的字符,则可以在仅 UCS-2 的正则表达式引擎中避免前一个问题。将它们替换为一个组

In other languages normalization takes place.

这是错误的。某些语言可能会在匹配正则表达式之前进行规范化,但这绝对不适用于所有“其他语言”

如果您想要更多保证,请使用 std::basic_regex<char8_t>std::basic_regex<char16_t>分别针对 UTF-8 和 UTF-16。你仍然需要一个支持 UTF-16 的库,否则它仍然只适用于只包含单词的正则表达式字符串

更好的解决方案可能是改用另一个库,例如 ICU regex .你可以查看Comparison of regular expression engines一些建议。它甚至有一列指示 native UTF-16 support对于每个库

相关:

另见

关于c++ - `std::wregex` 是否支持 utf-16/unicode 或仅支持 UCS-2?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59067280/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com