I am using the following data string and regexes to find each 5-letter word in a sentence, but I get incorrect results as indicated:
1 2 3 4 5 6 7 8 9 10 11
string sentence = "The quick brown fox jumped over the lazy dog,""and then ran away!";
/// finds 3 words : quick, brown, jumpe
regex FiveLetterWordsa {"(\\w{5})"};
/// finds 3 words : quick, brown, umped
regex FiveLetterWordsc {"(\\w{5}[^\\w]+)"};
/// finds 1 word: quick
regex FiveLetterWords {"([^\\w]+\\w{5}[^\\w]+)"};
What would be the correct regex to return the expected number of 5-letter words in the above sentence: (which is two)?
#include <iostream>
#include <string>
#include <regex>
#include <iterator> // std::distance
int main()
{
std::string s = "The quick brown fox jumped over the lazy dog,""and then ran away!";
std::regex five_letter_words("\\b[[:alnum:]]{5}\\b");
//or [:alpha:]
auto words_begin =
std::sregex_iterator(s.begin(), s.end(), five_letter_words);
auto words_end = std::sregex_iterator();
std::cout << "Found " << std::distance(words_begin, words_end) << " five-letter words:\n";
for (std::sregex_iterator i = words_begin; i != words_end; ++i)
{
std::cout << (*i).str() << " at position " << (*i).position() << '\n';
}
}