STL regex to match multiple substrings

Hi, I am using the (fairly) new STL implementation, which I just became aware of, of regexes. Seems to be an implementation of boost::regex ;)

Anyway, I have code, which I would like to use to get ALL matches within a string.

My String is: "Unseen University - Ankh-Morpork"

My regex is (simply): "Un" ;)

using code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
const char *reg_esp = "Un";


std::regex rgx(reg_esp);
                       
std::cmatch matches;
const char *target = "Unseen University - Ankh-Morpork";
 

if (std::regex_search(target, matches, rgx)) {
    
 
    const size_t n = matches.size();
    for (size_t a = 0; a < n; a++) {
        std::string str (matches[a].first, matches[a].second);
        std::cout << str << "\n";
    }
}


gives output:

"Un" (one line only). How do I get this to match ALL instances of "Un" (i.e. that the output is "Un\nUn", i.e Un two times)?

Cheers for any and all help!! :)

hansaaa :)
Each call to regex_search() generates one match. To get more than one, either call it in a loop, or use a regex iterator:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <regex>
#include <iostream>
#include <cstring>

int main()
{
    std::regex rgx("Un");
    const char *target = "Unseen University - Ankh-Morpork";
    for(auto it = std::cregex_iterator(target, target + std::strlen(target), rgx);
             it != std::cregex_iterator();
           ++it)
    {
        std::cmatch match = *it;
        std::cout << match.str() << '\n';
    }
}
Un
Un


Works with clang++/libc++, but liveworkspace is down at the moment, so I can't demo. Note that this won't work with GCC, where regex is not implemented so you have to use boost.regex if that's your platform.
Last edited on
Ok,that should work! Thanks! :)
Topic archived. No new replies allowed.