Logo
Articles Compilers Libraries Books MiniBooklets Assembly C++ Linux Others Videos
Advertisement

Article by Ayman Alheraki on January 11 2026 10:37 AM

Mastering stdregex in Modern C++ (C++11 – C++23)

Mastering std::regex in Modern C++ (C++11 – C++23)

 

1. Why Use std::regex?

Regular expressions allow you to search, match, and manipulate strings based on patterns, not fixed characters. They are powerful for:

  • Validating email addresses or phone numbers

  • Extracting words or numbers from a document

  • Replacing patterns within text

  • Parsing logs, configuration files, and even code

2. Required Headers and Setup

3. Main Types in <regex>

TypePurpose
std::regexHolds the regular expression pattern
std::smatchHolds match results for std::string
std::cmatchMatch results for C-style strings
std::regex_matchChecks if the whole string matches
std::regex_searchFinds a substring match in the string
std::regex_replaceReplaces matched text with a new string

 

4. regex_search vs regex_match

Example: regex_search (Searches for pattern anywhere in the text)

Example: regex_match (Full string must match)

5. regex_replace Example

6. Regex Pattern Syntax (Cheat Sheet)

Character Classes

SyntaxDescription
.Any character except newline
[abc]Matches any one of a, b, or c
[^abc]Not a, b, or c
[a-z]Lowercase letters
[0-9]Digits (0 to 9)
\wWord character [a-zA-Z0-9_]
\WNon-word character
\dDigit (0 to 9)
\DNon-digit character
\sWhitespace (space, tab, newline)
\SNon-whitespace character

 

Note: Use raw strings (R"(pattern)") in C++ to avoid escaping backslashes.

Quantifiers

SyntaxDescriptionExample
*0 or more repetitionsa*"", a, aa
+1 or more repetitionsa+a, aa
?0 or 1 occurrencea?"", a
{n}Exactly n timesa{3}aaa
{n,}At least n timesa{2,}aa, aaa
{n,m}Between n and m timesa{2,4}aa to aaaa

 

Anchors and Boundaries

SymbolDescription
^Start of string
$End of string
\bWord boundary
\BNot a word boundary

 

Grouping and Alternation

SyntaxDescription
(abc)Capturing group
(?:abc)Non-capturing group
`ab`

 

7. Real-World Examples

Validate Email

Extract All Words from a Sentence

Replace URLs with Placeholder

8. Error Handling

9. Using Regex Flags

FlagDescription
std::regex::icaseIgnore case
std::regex::ECMAScriptDefault syntax (JavaScript-like)
std::regex::basicPOSIX basic syntax
std::regex::extendedPOSIX extended syntax

 

10. Practice Tasks for Beginners

  1. Write a regex to validate phone numbers like +966-55-1234567

  2. Extract all IP addresses from a log file line

  3. Build a small command-line tool that replaces banned words in a sentence

  4. Validate hexadecimal color values like #FF5733 or #abc

Advertisements

Responsive Counter
General Counter
1000918
Daily Counter
118