Regular Expressions in C++

A regular expression (regex) is a sequence of characters that defines a search pattern. You use regex to find, match, or replace text based on rules rather than exact characters. Instead of searching for the exact word "apple", you can search for any word that starts with a vowel, or any sequence of digits, or any valid email address format.

C++11 introduced the <regex> header which brings full regex support into C++. You do not need any external library.

Think of regex like a filter template. You define the shape of what you want, and the regex engine scans through text to find everything that fits that shape.

Common Regex Symbols

┌─────────┬────────────────────────────────────────────────────────┐
│ Symbol  │ Meaning                                                │
├─────────┼────────────────────────────────────────────────────────┤
│ .       │ Any single character (except newline)                  │
│ *       │ 0 or more of the preceding character                   │
│ +       │ 1 or more of the preceding character                   │
│ ?       │ 0 or 1 of the preceding character (optional)           │
│ ^       │ Start of string                                        │
│ $       │ End of string                                          │
│ [abc]   │ Any one of: a, b, or c                                 │
│ [a-z]   │ Any character from a to z                              │
│ [^abc]  │ Any character except a, b, c                           │
│ \d      │ Any digit (0–9)                                        │
│ \w      │ Any word character (letter, digit, underscore)         │
│ \s      │ Any whitespace (space, tab, newline)                   │
│ |       │ OR: match left side or right side                      │
│ ()      │ Group: treat everything inside as one unit             │
│ {n}     │ Exactly n repetitions                                  │
│ {n,m}   │ Between n and m repetitions                            │
└─────────┴────────────────────────────────────────────────────────┘

Key Functions in <regex>

FunctionPurpose
regex_match()Check if the entire string matches the pattern
regex_search()Check if any part of the string matches the pattern
regex_replace()Replace matching parts with a new string
sregex_iteratorFind all matches in a string one by one

regex_match() — Full String Match

regex_match() checks whether the entire input string matches the pattern from start to end.

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

int main() {
    regex phonePattern("\\d{10}");   // exactly 10 digits

    string num1 = "9876543210";
    string num2 = "98765ABC10";

    cout << regex_match(num1, phonePattern) << endl;  // 1 (match)
    cout << regex_match(num2, phonePattern) << endl;  // 0 (no match)

    return 0;
}

Output:

1
0

Note: In C++ strings, a backslash must be written as \\. So \d becomes "\\d".

regex_search() — Partial Match

regex_search() finds a match anywhere inside the string. It does not require the full string to match.

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

int main() {
    string text = "My order number is 48291 and was placed today.";
    regex numPattern("\\d+");   // one or more digits

    smatch match;
    if (regex_search(text, match, numPattern)) {
        cout << "Found number: " << match[0] << endl;
    }

    return 0;
}

Output:

Found number: 48291

Finding All Matches with sregex_iterator

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

int main() {
    string text = "Prices: 10, 250, 30, 1999";
    regex numPattern("\\d+");

    sregex_iterator it(text.begin(), text.end(), numPattern);
    sregex_iterator end;

    cout << "All numbers found:" << endl;
    while (it != end) {
        cout << it->str() << endl;
        ++it;
    }

    return 0;
}

Output:

All numbers found:
10
250
30
1999

regex_replace() — Replace Matching Text

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

int main() {
    string text = "The cat sat on the mat near the bat.";
    regex pattern("(c|m|b)at");   // matches cat, mat, bat

    string result = regex_replace(text, pattern, "box");
    cout << result << endl;

    return 0;
}

Output:

The box sat on the box near the box.

Validating an Email Address

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

bool isValidEmail(const string& email) {
    regex emailPattern("[\\w.+-]+@[\\w-]+\\.[a-zA-Z]{2,}");
    return regex_match(email, emailPattern);
}

int main() {
    cout << isValidEmail("user@example.com")   << endl;  // 1
    cout << isValidEmail("bad-email@")         << endl;  // 0
    cout << isValidEmail("hello.world@co.in")  << endl;  // 1
    cout << isValidEmail("noatsign.com")       << endl;  // 0

    return 0;
}

Output:

1
0
1
0

Validating a Date Format (DD-MM-YYYY)

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

int main() {
    regex datePattern("\\d{2}-\\d{2}-\\d{4}");

    string d1 = "25-09-2026";
    string d2 = "2026-09-25";
    string d3 = "1-1-26";

    cout << regex_match(d1, datePattern) << endl;  // 1
    cout << regex_match(d2, datePattern) << endl;  // 0
    cout << regex_match(d3, datePattern) << endl;  // 0

    return 0;
}

Output:

1
0
0

Capturing Groups

Parentheses in a pattern create groups. You can extract specific parts of a match using group indices.

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

int main() {
    string dateStr = "Today is 18-09-2026.";
    regex datePattern("(\\d{2})-(\\d{2})-(\\d{4})");

    smatch m;
    if (regex_search(dateStr, m, datePattern)) {
        cout << "Full match: " << m[0] << endl;
        cout << "Day:        " << m[1] << endl;
        cout << "Month:      " << m[2] << endl;
        cout << "Year:       " << m[3] << endl;
    }

    return 0;
}

Output:

Full match: 18-09-2026
Day:        18
Month:      09
Year:       2026

Common Regex Patterns for Reference

Pattern PurposeRegex
Any digits only\\d+
Letters only[a-zA-Z]+
Alphanumeric\\w+
Exactly 6 digits\\d{6}
Starts with capital letter[A-Z][a-z]*
IP address (basic)\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}
Whitespace\\s+

Key Takeaways

  • Regular expressions define patterns for matching text — useful for validation, search, and replacement.
  • Include <regex> in C++11 and later — no external library needed.
  • regex_match() checks the entire string; regex_search() checks for a match anywhere inside.
  • regex_replace() replaces matched portions with a new string.
  • Use sregex_iterator to find all matches in a string.
  • Write backslashes as \\ inside C++ string literals when building regex patterns.

Leave a Comment

Your email address will not be published. Required fields are marked *