繁体   English   中英

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

[英]Do C++11 regular expressions work with UTF-8 strings?

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

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

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

我有一个用例,我需要处理潜在的 unicode字符串寻找笛卡尔坐标时,这个示例显示了我如何处理它作为建议std::wregexstd::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;
}

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM