我有一条蟒蛇正则表达式:
\A\s* # optional whitespace at the start, then
(?P<sign>[-+]?) # an optional sign, then
(?=\d|\.\d) # lookahead for digit or .digit
(?P<num>\d*) # numerator (possibly empty)
(?: # followed by
(?:/(?P<denom>\d+))? # an optional denominator
| # or
(?:\.(?P<decimal>\d*))? # an optional fractional part
(?:E(?P<exp>[-+]?\d+))? # and optional exponent
)
\s*\Z # and optional whitespace to finish换句话说,获取以下组的名称:
但我对C++11 regex格式感到困惑?正如我所读到的,支持的格式不多,但我得到了正则表达式解析器的例外。更多的是,我读到命名组不受C++11正则表达式的支持。
如何有一个C++11兼容的正则表达式,提供等价的方案?
非常感谢你的帮助。
发布于 2017-03-21 19:49:13
不能保留命名捕获组,但可以使用多行字符串文字来详细定义模式:
std::string pat = "^\\s*" // optional whitespace at the start, then
"([-+]?)" // an optional sign, then
"(?=\\.?\\d)" // lookahead for digit or .digit
"(\\d*)" // numerator (possibly empty)
"(?:" // followed by
"(?:/(\\d+))?" // an optional denominator
"|" // or
"(?:\\.(\\d*))?" // an optional fractional part
"(?:E([-+]?\\d+))?" // and optional exponent
")"
"\\s*$"; // and optional whitespace to finish
std::regex e(pat);
std::string s(" -23/34 ");
std::smatch a;
if (std::regex_search(s, a, e))
std::cout << a[0] << endl;https://stackoverflow.com/questions/42934997
复制相似问题