我必须在C ++中的正则表达式中使用unicode范围。基本上我需要的是有一个正则表达式来接受所有有效的unicode字符。我只是尝试了测试表达式并面临一些问题。
std::regex reg("^[\\u0080-\\uDB7Fa-z0-9!#$%&'*+/=?^_`{|}~-]+$");
问题出在\\u
?
答案 0 :(得分:5)
这应该可以正常工作,但您需要使用std::wregex
和std::wsmatch
。您需要将源字符串和正则表达式转换为 wide 字符unicode(Linux上为UTF-32,Windows上为UTF-16(ish))才能使其正常工作。
这适用于我的源文本为UTF-8
:
inline std::wstring from_utf8(const std::string& utf8)
{
// code to convert from utf8 to utf32/utf16
}
inline std::string to_utf8(const std::wstring& ws)
{
// code to convert from utf32/utf16 to utf8
}
int main()
{
std::string test = "john.doe@神谕.com"; // utf8
std::string expr = "[\\u0080-\\uDB7F]+"; // utf8
std::wstring wtest = from_utf8(test);
std::wstring wexpr = from_utf8(expr);
std::wregex we(wexpr);
std::wsmatch wm;
if(std::regex_search(wtest, wm, we))
{
std::cout << to_utf8(wm.str(0)) << '\n';
}
}
<强>输出:强>
神谕
注意:如果您需要UTF
转换库,我在上面的示例中使用了 THIS ONE 。
编辑或者,您可以使用此答案中提供的功能: