Matching Multiple Results with std::regex
Matching multiple results using std::regex can be a convenient way to extract multiple pieces of data from a string in a single operation. However, the provided regular expression "(bS*b){0,}" is not suitable for matching every word in the string "first second third forth".
Solution:
The issue with the original regular expression is that the quantifier {0,} matches zero or more times, which allows the pattern to match empty strings. Instead, a quantifier that matches once or more times, such as "{1,}" or " ", should be used.
Additionally, to match each word in the string, the regular expression must be applied repeatedly, searching each time from the position after the previous match. This can be achieved using a loop with regex_search iterating over the string.
Revised Code:
Here is a revised code that implements the necessary changes:
#include <iostream> #include <string> #include <regex> using namespace std; 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; }
This code iteratively applies the regular expression to the string and outputs each matching word separated by spaces. The output will be:
first second third forth
The above is the detailed content of How Can I Efficiently Extract Multiple Words from a String Using C \'s `std::regex`?. For more information, please follow other related articles on the PHP Chinese website!