我必须在 C++ 的正则表达式中使用 unicode 范围。基本上我需要的是有一个正则表达式来接受所有有效的 unicode 字符..我只是尝试使用测试表达式并面临一些问题。
std::regex reg("^[\\u0080-\\uDB7Fa-z0-9!#$%&'*+/=?^_`{|}~-]+$");
问题是与\\u
?
这应该可以正常工作,但你需要使用std::wregex
and 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';
}
}
Output:
神谕
Note:如果您需要一个UTF
我使用的转换库THIS ONE https://sourceforge.net/projects/utfcpp/在上面的例子中。
Edit:或者,您可以使用此答案中给出的功能:
C++ 字符串代码点和代码单元有什么好的解决方案吗? https://stackoverflow.com/questions/43302279/any-good-solutions-for-c-string-code-point-and-code-unit/43302460#43302460
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)