-3

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"

einpoklum
  • 118,144
  • 57
  • 340
  • 684
Hirsch Alter
  • 47
  • 1
  • 13
  • Yes, that is a regex. What are you trying to do? – Qix - MONICA WAS MISTREATED Jan 30 '17 at 07:18
  • Please take some time to read [the help pages](http://stackoverflow.com/help), especially the sections named ["What topics can I ask about here?"](http://stackoverflow.com/help/on-topic) and ["What types of questions should I avoid asking?"](http://stackoverflow.com/help/dont-ask). Also please [take the tour](http://stackoverflow.com/tour) and [read about how to ask good questions](http://stackoverflow.com/help/how-to-ask). Lastly please learn how to create a [Minimal, Complete, and Verifiable Example](http://stackoverflow.com/help/mcve). – Some programmer dude Jan 30 '17 at 07:22
  • @Someprogrammerdude: It looks like I figured out what OP was asking for; although, frankly, it may very well be a dupe. – einpoklum Jan 30 '17 at 16:01
  • @Qix: I think Someprogrammerdude's comment was somewhat more helpful than yours... – einpoklum Jan 30 '17 at 16:07

1 Answers1

0

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;
}
einpoklum
  • 118,144
  • 57
  • 340
  • 684