EN ·
🌏 中文

A Beginner's Guide to C++ Regular Expressions

Before the C++11 standard, handling regular expressions in C++ often required third-party libraries like Boost. With the release of C++11, the <regex> header was officially added to the standard library, allowing developers to perform efficient string matching, searching, and replacement directly using standard APIs.

Core Components

The std::regex library consists of several key components:

  1. std::regex: Defines the regular expression object.
  2. std::smatch: A container used to store match results (for std::string).
  3. std::regex_match: Attempts to match the entire target string.
  4. std::regex_search: Searches for a matching substring within the target string.
  5. std::regex_replace: Replaces the matched content.

Basic Usage Example

The following code demonstrates how to use std::regex_match to determine if a string conforms to a specific format:

#include <iostream>
#include <string>
#include <regex>

int main() {
    std::string text = "Hello, C++11";
    std::regex pattern("Hello, C\\+\\+\\d+");

    if (std::regex_match(text, pattern)) {
        std::cout << "Match successful!" << std::endl;
    } else {
        std::cout << "Match failed." << std::endl;
    }
    return 0;
}

Extracting Match Results

Using std::smatch, we can easily extract capture groups from a regular expression:

#include <iostream>
#include <string>
#include <regex>

int main() {
    std::string text = "User: Alice, ID: 12345";
    std::regex pattern("User: (\\w+), ID: (\\d+)");
    std::smatch matches;

    if (std::regex_search(text, matches, pattern)) {
        std::cout << "Username: " << matches[1] << std::endl;
        std::cout << "ID: " << matches[2] << std::endl;
    }
    return 0;
}

Important Considerations

By effectively utilizing these tools, C++ developers can greatly simplify complex text parsing tasks.