27

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

4

4 回答 4

16

您需要测试您的编译器和您正在使用的系统,但理论上,如果您的系统具有 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;
}

注意:这是在一个 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;
}

更新 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
于 2012-06-29T03:32:20.150 回答
2

C++11 正则表达式将“与”UTF-8 “一起工作”,对于“工作”的最小定义。如果您想要对 UTF-8 字符串的“完整”Unicode 正则表达式支持,最好使用直接支持该功能的库,例如http://www.pcre.org/

于 2012-06-29T01:10:23.337 回答
-1

是的,他们会的,这是 UTF-8 编码的设计。如果字符串被视为字节数组而不是代码点数组,则子字符串操作应该可以正常工作。

请参阅此处的常见问题解答 #18:http ://www.utf8everywhere.org/#faq.validation ,了解如何在此编码设计中实现这一点。

于 2012-06-29T20:46:32.880 回答
-1

我有一个用例,在查找笛卡尔坐标时我需要处理潜在的 unicode 字符串,这个示例显示了我如何按照建议处理它, std::wregex并且std::wstring针对解析模块的潜在unicode 字符。

static bool isCoordinate(std::wstring token)
{   
    std::wregex re(L"^(-?[[:digit:]]+)$");
    std::wsmatch match;
    return std::regex_search(token, match, re);
}

int wmain(int argc, wchar_t * argv[])
{
    // Testing against not a number nor unicode designation
    bool coord = ::isCoordinate(L"أَبْجَدِيَّة عَرَبِيَّة‎中文"); 

    if (!coord)
        return 0;
    return 1;
}
于 2018-06-08T03:36:50.050 回答