gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 03:49:25 25 4
gpt4 key购买 nike

根据各种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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com