Do C++11 regular expressions work with UTF-8 strings?(C++11 正则表达式是否适用于 UTF-8 字符串?)
问题描述
如果我想将 C++11 的正则表达式与 unicode 字符串一起使用,它们会将 char* 用作 UTF-8 还是我必须将它们转换为 wchar_t* 字符串?
If I want to use C++11's regular expressions with unicode strings, will they work with char* as UTF-8 or do I have to convert them to a wchar_t* string?
推荐答案
您需要测试您的编译器和您正在使用的系统,但理论上,如果您的系统具有 UTF-8 语言环境,它将受到支持.以下测试在 Clang/OS X 上为我返回 true.
You would need to test your compiler and the system you are using, but in theory, it will be supported if your system has a UTF-8 locale. The following test returned true for me on Clang/OS X.
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 编码的文件中编译的.
NOTE: This was compiled in a file what was UTF-8 encoded.
为了安全起见,我还使用了一个带有显式十六进制版本的字符串.它也有效.
Just to be safe I also used a string with the explicit hex versions. It worked also.
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("abcdxC3xA9""fg"), pattern);
std::locale::global(old);
return result;
}
<小时>
更新 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
这篇关于C++11 正则表达式是否适用于 UTF-8 字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++11 正则表达式是否适用于 UTF-8 字符串?


- 静态初始化顺序失败 2022-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- 如何对自定义类的向量使用std::find()? 2022-11-07
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- C++ 协变模板 2021-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01
- 从python回调到c++的选项 2022-11-16
- 近似搜索的工作原理 2021-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- Stroustrup 的 Simple_window.h 2022-01-01