What is a simple way to return the first part of a string that matches a regex in C++11?
Example: For the string "The great brown fox jumped over the lazy dog."
and the regexp /g[a-z]+/
the returned match would be "great"
What is a simple way to return the first part of a string that matches a regex in C++11?
Example: For the string "The great brown fox jumped over the lazy dog."
and the regexp /g[a-z]+/
the returned match would be "great"
Is this what you meant?
#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;
}
If you'd like that as a function, I'd allow myself to use 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
) instead. Having it available, you would write something like this:
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;
}
which you can use as follows:
#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;
}