C++ 11正则表达式是否适用于UTF-8字符串?

Mar*_*ark 26 c++ regex unicode utf-8 c++11

如果我想使用带有unicode字符串的C++ 11正则表达式,它们是否可以作为UTF-8使用char*,还是必须将它们转换为wchar_t*字符串?

Jef*_*mas 14

您需要测试编译器和正在使用的系统,但理论上,如果您的系统具有UTF-8语言环境,则会支持它.以下测试在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;
}
Run Code Online (Sandbox Code Playgroud)

注意:这是在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;
}
Run Code Online (Sandbox Code Playgroud)

更新 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
Run Code Online (Sandbox Code Playgroud)

  • 如果使用`u8"abcdéfg"`,则无需以UTF-8保存源代码. (3认同)