【问题标题】:c++ std regex question mark issuec++ std 正则表达式问号问题
【发布时间】:2013-04-13 11:27:37
【问题描述】:

我在使用标准正则表达式时遇到问题。我无法使问号量词起作用。对 regex_match 的调用将始终返回 0。

我也尝试过使用 {0,1},它的行为也不像我预期的那样:它的行为就像一个 + 量词。

这是我的代码:

#include <iostream>
#include <regex>
using namespace std;

int main(int argc, char **argv){

    regex e1("ab?c");
    cout << regex_match("ac", e1) << endl;    // expected : 1, output 0
    cout << regex_match("abc", e1) << endl;   // expected : 1, output 0
    cout << regex_match("abbc", e1) << endl;  // expected : 0, output 0

    regex e2("ab{0,1}c");
    cout << regex_match("ac", e2) << endl;    // expected : 1, output 0
    cout << regex_match("abc", e2) << endl;   // expected : 1, output 1
    cout << regex_match("abbc", e2) << endl;  // expected : 0, output 1

    return 0;
}

我使用以下命令编译:

g++ -std=c++11 main.cpp -o regex_test

我在这里做错了吗?或者为什么它不起作用?

【问题讨论】:

  • 据我所知,std::regex 没有正确/完全实施。 (但我不知道是这里的情况还是其他情况。)
  • 我尝试了 20 多种变体,转义 ?、括号、使用 *{x,y} 都以某种方式失败。我认为&lt;regex&gt; 有问题。
  • 是的,我听说过类似的事情,实际上可能就是这样。我已经切换到提升正则表达式(这有效),但我正在等待更多答案

标签: c++ regex std


【解决方案1】:

您的正则表达式代码很好。您正在使用的实现不是。它提供了一个标头,该标头声明了该库实施不佳的一堆东西。如果一个商业包这样做,它会受到严厉的批评,这是正确的。一分钱一分货。

【讨论】:

    【解决方案2】:

    str::regex 大部分没有在 gcc 中实现(在撰写本文时)。见第 28 节: http://gcc.gnu.org/onlinedocs/libstdc++/manual/status.html#status.iso.2011

    【讨论】:

      【解决方案3】:

      正则表达式的 POSIX 标准定义了两种类型,基本和扩展。这 ?运算符是一个扩展功能。显然你使用

      std::regex re2(".*(a|xayy)", std::regex::extended)
      

      获取扩展功能。

      【讨论】:

      • 很高兴知道。但是我在我的代码中测试了它,它仍然不起作用(与以前的输出相同)
      • 这是一种方法,但简单的std::regex re2(".*(a|xayy)"); 也可以。默认的正则表达式语法是 ECMAScript,开箱即用支持?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-31
      • 2023-03-29
      • 1970-01-01
      • 2011-08-13
      • 2013-05-26
      • 1970-01-01
      相关资源
      最近更新 更多