Home > Backend Development > C++ > How Can I Efficiently Match Multiple Words in a String Using C \'s `std::regex`?

How Can I Efficiently Match Multiple Words in a String Using C \'s `std::regex`?

DDD
Release: 2024-11-29 12:51:11
Original
377 people have browsed it

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;
}
Copy after login

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:

  1. The regex_search function searches for the first occurrence of the pattern within the substring starting at searchStart.
  2. If a match is found, we print the matching word.
  3. We update the searchStart iterator to start searching after the matched word.

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template