【发布时间】:2018-12-01 02:58:18
【问题描述】:
我想要一个像“.c”这样的模式,匹配“.”任何 utf8 后跟 'c' 使用 std::regex。
我在 Microsoft C++ 和 g++ 下尝试过。我得到相同的结果,每次“。”只匹配一个字节。
这是我的测试用例:
#include <stdio.h>
#include <iostream>
#include <string>
#include <regex>
using namespace std;
int main(int argc, char** argv)
{
// make a string with 3 UTF8 characters
const unsigned char p[] = { 'a', 0xC2, 0x80, 'c', 0 };
string tobesearched((char*)p);
// want to match the UTF8 character before c
string pattern(".c");
regex re(pattern);
std::smatch match;
bool r = std::regex_search(tobesearched, match, re);
if (r)
{
// m.size() will be bytes, and we expect 3
// expect 0xC2, 0x80, 'c'
string m = match[0];
cout << "match length " << m.size() << endl;
// but we only get 2, we get the 0x80 and the 'c'.
// so it's matching on single bytes and not utf8
// code here is just to dump out the byte values.
for (int i = 0; i < m.size(); ++i)
{
int c = m[i] & 0xff;
printf("%02X ", c);
}
printf("\n");
}
else
cout << "not matched\n";
return 0;
}
我希望模式“.c”与我的 tobesearched 字符串的 3 个字节匹配,其中前两个是 2 个字节的 utf8 字符,后跟“c”。
【问题讨论】:
-
使用宽字符和 UTF32(如果你的编译器只支持 UTF16),或者使用支持 UTF-8 的第三方正则表达式库。标准 C++ 中没有解决方案。
-
所以基本上
std::regex不支持utf8?我确实有另一个确实的正则表达式库,但我期待标准库支持这一点。 -
标准中的 Unicode 支持几乎不存在。