C++ 如何从std::regex_错误中获取解释性字符串?
我的程序正在抛出一个C++ 如何从std::regex_错误中获取解释性字符串?,c++,regex,c++11,error-handling,C++,Regex,C++11,Error Handling,我的程序正在抛出一个std::regex\u错误()。我想知道错误是什么,因为正则表达式在我看来是合法的。我基本上是这样做的: try { // offending code } catch (std::regex_error& e) { log_error("Regex error: " << e.what() << ", " << e.code()); } 这不是特别有用。4是什么意思?政府只说: 返回传递给std::regex_
std::regex\u错误()。我想知道错误是什么,因为正则表达式在我看来是合法的。我基本上是这样做的:
try {
// offending code
} catch (std::regex_error& e) {
log_error("Regex error: " << e.what() << ", " << e.code());
}
这不是特别有用。4是什么意思?政府只说:
返回传递给std::regex_错误构造函数的std::regex_常量::error_类型
的条目提供错误代码列表,所有错误代码的精确值均为“未指定”
我除了做这样的事之外别无选择吗
switch (e.code()) {
case std::regex_constants::error_collate: return "error_collate";
case std::regex_constants::error_ctype: return "error_ctype";
// etc ...
}
使用开关
的另一种方法是为每个regex错误代码定义自己的枚举,并将结果转换为该枚举,从而为您提供更好的运行时调试帮助
enum class RegexError {
collate = std::regex_constants::error_collate,
ctype = std::regex_constants::error_ctype,
// etc
};
RegexError errorCode = static_cast<RegexError>( e.code() );
// your debugger will now show you what the meaning of errorCode is
enum类regexeror{
collate=std::regex\u常量::错误\u collate,
ctype=std::regex_常量::error_ctype,
//等
};
RegexError errorCode=static_cast(e.code());
//调试器现在将向您显示错误代码的含义
这样就不需要使用字符串
但是,如果要以可读的方式向用户显示错误,则需要使用字符串,但可以使用映射来存储它们:
map<RegexError, wchar_t const * const> errorMessages;
errorMessages[RegexError::collate] = L"the expression contains an invalid collating element name";
errorMessages[RegexError::ctype ] = L"the expression contains an invalid character class name";
// etc
映射错误消息;
errorMessages[RegeXeror::collate]=L“表达式包含无效的排序元素名称”;
errorMessages[RegeXeror::ctype]=L“表达式包含无效的字符类名”;
//等
> p>这是标准C++库中实现问题的一个质量,这是一个很好的方式,说明它是一个bug。确切地说(“std::regex_error::what()应该说明错误代码”)
在bug报告中有一个最近提交的补丁,所以我想它最终会显示为一个升级。[更新:根据上面的错误报告,它在v6.1(2016年4月26日发布)中已修复,但直到2018年11月19日,错误报告才被标记为已解决。无论如何,如果您有一个合理的最新发行版,这应该不再是问题。]
同时,除了使用自己的代码->消息转换功能,您几乎没有其他选择。(或者,作为一种临时调试方法,请参阅代码>包含/Buts/RexEXORLION.H./COD>)/P>如果使用标准C++库的GNU实现,4是括号错误。这让我非常难过!我暂时采取了查阅regex_error.h的方法。@Claudiu:的确如此。尽管如果trunk中没有补丁的话会更难过(在这种情况下,我可能会建议使用LLVM项目的补丁)
map<RegexError, wchar_t const * const> errorMessages;
errorMessages[RegexError::collate] = L"the expression contains an invalid collating element name";
errorMessages[RegexError::ctype ] = L"the expression contains an invalid character class name";
// etc