Home >Backend Development >C++ >How Can I Efficiently Match Multiple Words in a String Using C \'s `std::regex`?
Matching Multiple Results with std::regex
Matching multiple occurrences of words in a string can be challenging with regular expressions. Although the expression "(bS*b){0,}" appears to match all consecutive words in a string, it may not yield the desired output. Instead, an iterative approach is recommended.
Following is the revised code:
#include <iostream> #include <string> #include <regex> int main() { regex exp("(\b\S*\b)"); smatch res; string str = "first second third forth"; string::const_iterator searchStart(str.cbegin()); while (regex_search(searchStart, str.cend(), res, exp)) { cout << (searchStart == str.cbegin() ? "" : " ") << res[0]; searchStart = res.suffix().first; } cout << endl; return 0; }
In this updated code, we use a while loop to iterate through the string while performing regular expression searches. The loop starts by setting the searchStart iterator to the string's beginning. Then, within each iteration:
By iterating through the string until no more matches are found, we can output all the words one by one.
The above is the detailed content of How Can I Efficiently Match Multiple Words in a String Using C \'s `std::regex`?. For more information, please follow other related articles on the PHP Chinese website!