1

I am trying to get multiple variables from a single regex match.

std::string string_to_search = "abc def ghi";
std::regex pattern = "abc (.+) (.+)";
regex_search(string_to_search);
std::string segment1 = //assign to first [a-z]*
std::string segment2 = //assign to second [a-z]*

In ruby what I am trying to do is

case string_to_search

    when /\Aabc (.+) (.+)/
        segment1 = $1
        segment2 = $2
end
4
  • What problem are you facing? Commented Feb 16, 2015 at 1:47
  • I don't know how to separate the string into separate variables based on the pattern. Commented Feb 16, 2015 at 1:48
  • Have you examined the functions exposed in <regex> and tried calling one with valid parameters, you know, to start? Commented Feb 16, 2015 at 1:57
  • I was looking at regex_iterator, but that would require me to create multiple regexes(regi?) which I guess I could do, but I was hoping wouldn't be necessary. Commented Feb 16, 2015 at 2:00

1 Answer 1

1

The two groups can be obtained as follows:

std::string string_to_search = "abc def ghi";
std::regex pattern ("abc (.+) (.+)");
std::smatch base_match;


if (std::regex_match(string_to_search, base_match, pattern))
{
    std::cout << base_match[1] << endl; // def
    std::cout << base_match[2] << endl; // ghi
}

Description of regex_match and how to use it is here.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.