首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C++11正则混淆

C++11正则混淆
EN

Stack Overflow用户
提问于 2017-03-21 18:08:16
回答 1查看 58关注 0票数 1

我有一条蟒蛇正则表达式:

代码语言:javascript
复制
\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兼容的正则表达式,提供等价的方案?

非常感谢你的帮助。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-03-21 19:49:13

不能保留命名捕获组,但可以使用多行字符串文字来详细定义模式:

代码语言:javascript
复制
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;

C++演示

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42934997

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档