使用现代 C++ return 字符串中第一个正则表达式匹配的简单方法是什么?

What's a simple way to return the first regex match in a string with modern C++?

在 C++11 中 return 匹配正则表达式的字符串的第一部分的简单方法是什么?

示例:对于字符串 "The great brown fox jumped over the lazy dog." 和正则表达式 /g[a-z]+/,returned 匹配将为 "great"

你是这个意思吗?

#include <regex>
#include <iostream>

// ... include first_match() somewhere...

int main()
{
    std::string subject("The great brown fox jumped over the lazy dog.");
    std::string result;
    std::regex re("g[a-z]+");
    std::smatch match;
    if (std::regex_search(subject, match, re)) { std::cout << match.str(0); }
    else { std::cout << "(No matches)"; }
    std::cout << '\n';
    return 0;
}

如果您希望将其作为一个函数,我允许自己使用 std::optional. It's part of C++17, not C++11, but it's already available in C++14 as std::experimental::optional, and for C++11 you can use Boost's boost::optional) 代替。有了它,你会写这样的东西:

std::optional<std::string> first_match(
    const std::string&  str, 
    const std::regex&   expression)
{
    std::smatch match;
    return std::regex_search(str, match, expression) ?
        std::optional<std::string>(match.str(0)) : std::nullopt;
}

您可以按如下方式使用:

#include <regex>
#include <iostream>
#include <optional>

int main()
{
    std::cout <<
        first_match(
            "The great brown fox jumped over the lazy dog.", "g[a-z]+"
        ).value_or("(no matches)") << '\n';
    return 0;
}