如果我想将 C++11 的正则表达式与 unicode 字符串一起使用,它们是否可以将 char* 作为 UTF-8 使用,还是必须将它们转换为 wchar_t* 字符串?
您需要测试您的编译器和您正在使用的系统,但理论上,如果您的系统具有 UTF-8 语言环境,它将受到支持。以下测试在 Clang/OS X 上对我返回 true。
bool test_unicode()
{
std::locale old;
std::locale::global(std::locale("en_US.UTF-8"));
std::regex pattern("[[:alpha:]]+", std::regex_constants::extended);
bool result = std::regex_match(std::string("abcdéfg"), pattern);
std::locale::global(old);
return result;
}
注意:这是在 UTF-8 编码的文件中编译的。
为了安全起见,我还使用了带有显式十六进制版本的字符串。它也起作用了。
bool test_unicode2()
{
std::locale old;
std::locale::global(std::locale("en_US.UTF-8"));
std::regex pattern("[[:alpha:]]+", std::regex_constants::extended);
bool result = std::regex_match(std::string("abcd\xC3\xA9""fg"), pattern);
std::locale::global(old);
return result;
}
Update test_unicode()
对我来说仍然有效
$ file regex-test.cpp
regex-test.cpp: UTF-8 Unicode c program text
$ g++ --version
Configured with: --prefix=/Applications/Xcode-8.2.1.app/Contents/Developer/usr --with-gxx-include-dir=/usr/include/c++/4.2.1
Apple LLVM version 8.0.0 (clang-800.0.42.1)
Target: x86_64-apple-darwin15.6.0
Thread model: posix
InstalledDir: /Applications/Xcode-8.2.1.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)