STL regex to match multiple substrings
Apr 17, 2013 at 12:54am Apr 17, 2013 at 12:54am UTC
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 :)
Apr 17, 2013 at 2:11am Apr 17, 2013 at 2:11am UTC
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 Apr 17, 2013 at 2:12am Apr 17, 2013 at 2:12am UTC
Apr 17, 2013 at 3:20pm Apr 17, 2013 at 3:20pm UTC
Ok,that should work! Thanks! :)
Topic archived. No new replies allowed.