如何使用 std::regex 查找字符串中的下一个匹配项

How to use std::regex to find the next match in a string?

本文关键字:下一个 字符串 何使用 std regex 查找      更新时间:2023-10-16

尝试在扫描仪中使用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: %sn", matches[0]);
    }
    else 
        puts("No match.");
}

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

相反,如果输入" 500"它应该返回 false。

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

谢谢。

更改 regex_matchregex_search . 第二个参数是多余的:

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

此外,matches [0]不是 c 字符串,而是 std:: sub_match <char const *> const 。 如果不编写以下内容,则无法将其传递给printf

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

但是,它对于流来说是重载的,因此您可以改为 std:: cout << matches [0] .

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

这必须与 std::regex_iterator 有关,请参阅有关详细信息(包括示例(http://en.cppreference.com/w/cpp/regex/regex_iterator

相关文章: