2

I have been looking for a good way to calculate the number of sub-strings of a particular type in a string, say, I want to count the occurrences of 'sms' in the string 'smstyuismsms'. I found an answer in a forum where somebody suggested making use of regex_iterator. But, when I tried it as follows:

string in = "smstyuismssms";
cout << distance(regex_iterator(in.begin(), in.end(), regex("sms")),regex_iterator()) << "\n";

It throws an error saying

error: missing template arguments before '(' token

So, if not this, then what is the correct way of using regex template? Please provide some examples as well.

unixia
  • 4,102
  • 1
  • 19
  • 23

1 Answers1

3

By looking at the documentation, it seems std::regex_iterator is the template from which four instantiations exist:

cregex_iterator    regex_iterator<const char*>
wcregex_iterator   regex_iterator<const wchar_t*>
sregex_iterator    regex_iterator<std::string::const_iterator>
wsregex_iterator   regex_iterator<std::wstring::const_iterator>

you should use these instead. I mean, you can always pass the template argument yourself but that's needlessly verbose.

From the cppreference example:

auto words_begin = std::sregex_iterator(s.begin(), s.end(), words_regex);

This is much like std::string/std::wstring which are both instantiations of the std::basic_string template. Basically your code is the equivalent of using basic_string and not passing the template argument instead of using string/wstring directly.

Borgleader
  • 15,826
  • 5
  • 46
  • 62
  • Hi! I first tried it by using the same example only. But sregex_iterator threw an error "undefined reference to regex". When I searched for the issue, I found that the compiler that I am using(gcc4.8.1) probably doesn't support this instantiation. So, then, I switched to regex_iterator. – unixia May 26 '15 at 14:43
  • 1
    @timidgeek [See this question](http://stackoverflow.com/questions/12530406/is-gcc-4-7-and-gcc-4-8-buggy-about-regular-expressions), I'm afraid your compiler might be too old. – Borgleader May 26 '15 at 14:46
  • Fine. I'll update my compiler and ask if any problem persists. Thank you. – unixia May 26 '15 at 15:23