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

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

Barbara Streisand
Release: 2024-12-15 08:17:16
Original
446 people have browsed it

How Can I Efficiently Extract Multiple Words from a String Using C  's `std::regex`?

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

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

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template