C++ Standard Library<regex>

In the C++ standard library, the<regex>header file provides regular expression functionality, allowing developers to search, replace, or split strings in a very flexible way. Regular expressions are a powerful text processing tool, widely used in fields such as data validation, text analysis, and pattern matching.

A regular expression is a pattern that uses a single string to describe and match a series of strings conforming to a certain syntax rule. In C++, regular expressions are implemented through<regex>Library implementation.

In C++11's<regex>When using regular expressions, you need to escape backslashes in string literals.\escape it, that is, write it as a double backslash\\。

Why double backslash?

The C++ compiler processes escape characters in string literals first, while the regex engine processes them afterwards.

For example, you write\d+, the compiler will\dit will be treated as an unknown escape character, causing an error, or becomed, the correct syntax\\d+, the compiler first\\convert to\, and when the regex engine then reads\d。

C++11 also supports raw strings, which can avoid double backslashes and are very suitable for writing complex regexes:
regex re(R"(\d+)");         // 原始字符串,不需要写 \\d
  • The content inside R"(...)" will not undergo escape processing.
  • It is recommended to use this when writing complex regexes with multiple backslashes.

Basic Syntax

Basic components of regular expressions

  • character class: such as[abc]Indicates matching any one character among a, b, or c.
  • quantifier: such as*(zero or more times),+(one or more times),?(zero or one time).
  • boundary matching: such as^(start of line),$(end of line).
  • grouping: using parentheses()to create a group.

C++ <regex>Main classes and functions of the library

  • std::regex: represents a regular expression object.
  • std::regex_match: Checks whether the entire string matches the regular expression.
  • std::regex_search: searches the string for parts that match the regular expression.
  • std::regex_replace: Replaces the parts of the string that match the regular expression.
  • std::sregex_iterator: An iterator, used to traverse all matches.

Example

1. Overall matching: regex_match

Example

#include <iostream>
#include <regex>
using namespace std;

int main() {
    regex re("\\d+");          // match digits
    string s = "12345";

    if (regex_match(s, re))
        cout << "Match successful\n";
    else
        cout << "Match failed\n";
}

Output result:

Match successful

2. Check whether the string matches the regular expression

Example

#include <iostream>
#include <string>
#include <regex>
using namespace std;

int main() {
    string text = "Hello, World!";
    regex pattern("^[a-zA-Z]+, [a-zA-Z]+!$");

    if (regex_match(text, pattern)) {
        cout << "The string matches the pattern." << endl;
    } else {
        cout << "The string does not match the pattern." << endl;
    }

    return 0;
}

Output result:

The string matches the pattern.

3. Search for matches in a string

Example

#include <iostream>
#include <string>
#include <regex>
using namespace std;

int main() {
    string text = "123-456-7890 and 987-654-3210";
    regex pattern("\\d{3}-\\d{3}-\\d{4}");

    smatch matches;
    while (regex_search(text, matches, pattern)) {
        cout << "Found: " << matches[0] << endl;
        text = matches.suffix().str();  // continue searching the rest
    }

    return 0;
}

Output result:

Found: 123-456-7890
Found: 987-654-3210

4. Replace matched items in the string

Example

#include <iostream>
#include <string>
#include <regex>
using namespace std;

int main() {
    string text = "Hello, World!";
    regex pattern("World");
    string replacement = "Universe";

    string result = regex_replace(text, pattern, replacement);

    cout << "Original: " << text << endl;
    cout << "Modified: " << result << endl;

    return 0;
}

Output result:

Original: Hello, World!
Modified: Hello, Universe!

More content

Common classes and types

Name Description
std::regex Compile the regular expression object
std::smatch std::stringMatch Result
std::cmatch C string match results (const char*)
std::sregex_iterator used forstd::stringmatch iterator
std::cregex_iterator Match iterator for C strings
std::syntax_option_type Regular expression syntax options
std::match_flag_type Match control flags

Common Functions

Function Name Purpose Return Value Example
regex_match(s, re) Check whether the entire string matches bool regex_match("123", re)
regex_search(s, m, re) Find the first match bool regex_search(s, m, re)
regex_replace(s, re, fmt) replace matches string regex_replace(s, re, "#")

smatchMatch result object

member Description Example
m.str() Return the entire matched content cout << m.str()
m[i] Return the i-th capture group m[1].str()
m.position() Match start position m.position(0)
m.size() capture group count m.size()
m.empty() Whether the match is empty m.empty()

Common regular expression syntax

symbol Meaning Example
. any character a.cmatchabc
\d Numbers \d+
\w Alphanumeric and underscore \w+
\s whitespace character \s+
^ beginning ^abc
$ end xyz$
+ 1 or more times a+
* 0 or more times a*
? 0 or 1 time a?
{n,m} n~m times \d{2,4}
() capturing group (ab)+
[] character set [A-Z]
` ` or `cat dog`

In the C++ source code string, you need to write\\dinstead of\d, because\needs to be escaped.

Typical usage examples

Example

#include <iostream>
#include <regex>
using namespace std;

int main() {
    regex re("\\d+");
    string s = "abc123def456";

    // Find the first match
    smatch m;
    if (regex_search(s, m, re))
        cout << "First match: " << m.str() << endl;

    // Iterate over all matches
    for (sregex_iterator it(s.begin(), s.end(), re), end_it; it != end_it; ++it)
        cout << "Matched: " << it->str() << endl;

    // Replace
    string result = regex_replace(s, re, "#");
    cout << result << endl;
}
other extensions