std::match_results::str(3)

πŸ“¦ version 2024.07.05, in nixpkgs unstable, opensuse-leap 16.0

Hey bestie πŸ’– welcome to the std::match_results::str(3) page from the C++ Standard Libary manual (yes, spelled exactly like that, no cap). This is the iconic little member that hands you back a match as a string. Let’s get into it πŸŽ€


πŸ’– NAME πŸ’–

std::match_results::str β€” std::match_results::str

yes bestie, the NAME section really said that twice 😭 iconic behavior


✨ Synopsis ✨

Okay so here’s the signature, literally:

string_type str( size_type n = 0 ) const;  (since C++11)

It returns a string representing the indicated sub-match 🫢

  • If n == 0, you get a string representing the entire matched expression. the whole thing, main character energy.
  • If 0 < n && n < size(), you get a string representing the n^th sub-match. sub-match moment.
  • If n >= size(), you get a string representing the unmatched match. no cap, that’s what it says.

The call is equivalent to string_type((*this)[n]); β€” that’s the whole vibe πŸ”₯


πŸŽ€ Parameters πŸŽ€

  • n β€” an integral number specifying which match to return.

🌸 Return value 🌸

Returns a string representing the specified match or sub match. slay


πŸ¦‹ Example πŸ¦‹

Run this code, bestie:

// Run this code

#include <iostream>
#include <regex>
#include <string>

int main()
{
    std::string target("baaaby");
    std::smatch sm;

    std::regex re1("a(a)*b");
    std::regex_search(target, sm, re1);
    std::cout << "entire match: " << sm.str(0) << '\n'
              << "submatch #1: " << sm.str(1) << '\n';

    std::regex re2("a(a*)b");
    std::regex_search(target, sm, re2);
    std::cout << "entire match: " << sm.str(0) << '\n'
              << "submatch #1: " << sm.str(1) << '\n';
}

πŸ’œ Output πŸ’œ

entire match: aaab
submatch #1: a
entire match: aaab
submatch #1: aa

πŸ‘‘ See also πŸ‘‘

  • operator[] β€” returns specified sub-match (public member function). iykyk

xoxo, your regex bestie πŸ’– β€” source: http://cppreference.com, dated 2024.06.10.

πŸ“¦ where this page comes from