regex - Finding each vowel in a sentence

I am trying to write a program that uses the regex_search() function to find _each_ vowel in a sentence.

The regex_search() function call is as follows:

1
2
3
4
    bool found = regex_search (data,
                               m, 
                               regex { "([aeiou]+)" });


http://cpp.sh/35g3p

However, this regex finds only the 1st vowel in the sentence. I want _every_ vowel returned in an smatch object.

What is the right regex for that purpose?

Thanks.
I am not sure if possible with regex_search, but regex_iterator works.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <regex>
#include <iterator>
#include <iostream>
#include <string>

int main()
{
  const std::string s = "Quick brown fox.";

  std::regex words_regex("[aeiou]");
  auto words_begin =
    std::sregex_iterator(s.begin(), s.end(), words_regex);
  auto words_end = std::sregex_iterator();

  std::cout << "Found "
    << std::distance(words_begin, words_end)
    << " words:\n";

  for (std::sregex_iterator i = words_begin; i != words_end; ++i) 
  {
    std::smatch match = *i;
    std::string match_str = match.str();
    std::cout << match_str << '\n';
  }
}

http://en.cppreference.com/w/cpp/regex/regex_iterator

Output

Found 4 vowels:
u
i
o
o
couple of additions that you may wish to consider:
(a) std::regex_constants::icase - for case insensitive searches
(b) position() member function for std::match_results for the vowels' location:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <regex>
#include <iterator>
#include <iostream>
#include <string>

int main()
{
  const std::string s = "Quick brown fOx.";

  std::regex words_regex("[aeiou]", std::regex_constants::icase);
  auto words_begin =
    std::sregex_iterator(s.begin(), s.end(), words_regex);
  auto words_end = std::sregex_iterator();

  std::cout << "Found " << std::distance(words_begin, words_end) << " vowels:\n";

  for (std::sregex_iterator i = words_begin; i != words_end; ++i)
  {
    std::cout << (*i).str() << " at position " << (*i).position() << '\n';
  }
}

Topic archived. No new replies allowed.