c++ - 正则表达式匹配 Unicode 'Punctuation' 类别 c++

标签 c++ regex c++11 unicode

根据各种documentation ,要匹配任何标点符号我需要使用“\p{P}”模式

#include <regex>
#include <string>

...

std::string str = "Hello'\"#%&!.:,?¿World";
std::regex re("\\p{P}", std::regex::extended );
str = std::regex_replace(str, re, " ");

但是当我执行上述操作时出现错误,所以我的问题是,如何匹配所有标点符号\p{P}?

最佳答案

在我的环境中,您程序的这个 wchar_t 版本按预期工作:

#include <regex>
#include <string>
#include <iostream>
#include <locale>

int main ()
{
    std::locale::global(std::locale(""));

    std::wstring str =L"Hello'\"#%&!.:,?¿World";
    std::basic_regex<wchar_t> re(L"[[:punct:]]", std::regex::extended );
    str = std::regex_replace(str, re, L" ");
    std::wcout << str << std::endl;
}

我在 Linux 上同时使用 g++ 和 clang++(带有 libc++)。没有人可以对您的环境做出任何保证,但我敢猜测最新的 VS 也应该可以工作。 char32_t 在 Windows/VS 平台上可能是也可能不是比 wchar_t 更好的选择。 VS并不完全符合标准,它的wchar_t不能代表扩展字符集的所有元素。它基本上是一个 UTF-16 代码点。因此,如果您在 BMP 之外使用标点符号,则 wchar_t 正则表达式可能会失败。 char32_t 正则表达式不适用于任何一个 Linux 编译器/库; YMMV.

如果您想直接对 UTF-8 编码的字节字符串进行操作,我猜您不适合使用标准 C++ 库。您需要第三方正则表达式库,例如 PCRE .或者,即时转换 UTF-8 编码的字符串:

#include <regex>
#include <string>
#include <iostream>
#include <locale>
#include <codecvt>

int main ()
{
    std::locale::global(std::locale("en_US.utf8"));

    std::string str ="Hello'\"#%&!.:,?¿World";
    std::regex re("[[:punct:]]", std::regex::extended ); // ¡No trabajo!
    str = std::regex_replace(str, re, " ");
    std::cout << str << std::endl;

    std::wstring_convert<std::codecvt_utf8<wchar_t>, wchar_t> wconv;

    std::wstring wstr =  wconv.from_bytes(str);
    std::basic_regex<wchar_t> wre(L"[[:punct:]]", std::regex::extended );
    wstr = std::regex_replace(wstr, wre, L" ");
    str = wconv.to_bytes(wstr);
    std::cout << str << std::endl;
}

关于c++ - 正则表达式匹配 Unicode 'Punctuation' 类别 c++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32572555/

相关文章:

c++ - 减少 wiimote 俯仰/滚动变化

c++ - cygwin下如何改用g++ mingw工具链

python - 在开始和结束处匹配相同的模式两次

regex - 当我使用一字符长字符集时,为什么我的正则表达式不匹配?

c++ - 如何在 Visual C++ 2010 或 2008 中使用 OpenCV 2.1 访问网络摄像头(compro IP50W)

C++,如何只打印出字符串的第一部分?

javascript - 正则表达式找到独特的词

c++ - CMD 中的随机数生成器 C++ 错误

c++ - 在嵌套类中声明固定长度的数组

c++ - 关于 C++ 类中的转换