【问题标题】:How to use std::regex to find the next match in a string?如何使用 std::regex 在字符串中查找下一个匹配项?
【发布时间】:2015-02-22 17:31:55
【问题描述】:

试图在扫描仪中使用std::regex。因此,在我的情况下,它应该做的就是找到从输入序列的const char *p 开始的第一个匹配项。它不应该跳过任何东西。只要表达式有效,它就需要匹配。然后返回它得到的。

这可能吗?

这是我卑微的尝试:

#include <regex>

static void Test()
{
    const char *numbers = "500 42 399 4711";
    std::regex expr("[0-9]+");
    std::match_results<const char *> matches;
    if (std::regex_match
            (&numbers[0]
            ,&numbers[strlen(numbers)]
            , matches
            , expr
            , std::regex_constants::match_continuous))
    {
        printf("match: %s\n", matches[0]);
    }
    else 
        puts("No match.");
}

我正在寻找的是它只返回 "500" 作为成功匹配。但我什至无法让它返回 true...

相比之下,如果输入 " 500" 它应该返回 false。

std::regex_search() 似乎也没有做我想做的事。它试图找到每个匹配项,而不仅仅是第一个匹配项。

谢谢。

【问题讨论】:

  • 你肯定需要regex_search。而printf("match: %s\n", matches[0]); 是完全错误的。
  • 要是我能到那里就好了 ;)
  • [0-9]+ 没问题。这是关于那些新的正则表达式类的处理。他们似乎很好地隐藏了我的用例。还有一些 regex_iterator 但它似乎也在查看所有输入而不是在 1 场比赛后停止。 (昂贵)
  • 您为什么认为regex_search 会尝试找到所有匹配项?它没有。

标签: c++ regex c++11 std


【解决方案1】:

改变 regex_matchregex_search。第二个参数是多余的:

if (std::regex_search
        (numbers
        , matches
        , expr
        , std::regex_constants::match_continuous)) { ... }

另外,matches [0] 不是 c 字符串,而是 std:: sub_match &lt;char const *&gt; const。你不能把它传递给printf 而不写下类似的东西:

printf ("match: %s", matches[0].str ().c_str ());

不过,它对于流来说是重载的,所以你可以改为 std:: cout &lt;&lt; matches [0]

看到它运行: https://ideone.com/ChqQIb

【讨论】:

  • 有了 /that/ 文档,我希望匹配项包含所有匹配项,而不仅仅是一个……非常感谢。
【解决方案2】:

这必须与 std::regex_iterator 一起做,详情请参阅(包括示例)http://en.cppreference.com/w/cpp/regex/regex_iterator

【讨论】:

  • 虽然答案可以参考外部页面以获得更深入的解释,但答案本身至少应包含基本解决方案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多