The C++ standard library
The C++ standard library's The header provides regular expression functionality, allowing developers to use a very flexible way to search, replace, or split strings. 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 that conform to certain syntactic rules. In C++, regular expressions are implemented through the library.
In C++11's , when using regular expressions, you need to escape the backslash \ in string literals, that is, write it as a double backslash \\.
Why use a double backslash?
The C++ compiler processes the escape characters in string literals first, while the regex engine processes them afterward.
For example, if you write \d+, the compiler will treat \d as an unknown escape character and report an error, or turn it into d, the correct way to write it is \\d+, the compiler first converts \\ into \, and then the regex engine reads \d.
C++11 also supports raw strings, which can avoid double backslashes and are very suitable for writing complex regular expressions:regex re(R"(\d+)"); // 原始字符串,不需要写 \\d
Basic Syntax
Basic composition of regular expressions
- Character class: Such as
[abc]matches any one of the characters 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: Use parentheses
()to create a group.
C++ 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. Whole match: regex_match
Example
#include
#include
using
namespace
std
;
int
main
(
)
{
regex re
(
"\d+"
)
;
// Match digits
string s
=
"12345"
;
if
(
regex_match
(
s, re
)
)
cout
<<
"Match succeeded\n"
;
else
cout
<<
"Match failed\n"
;
}
Output result:
匹配成功
2. Check whether a string matches a regular expression
Example
#include
#include
#include
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
#include
#include
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 remaining part
}
return
0
;
}
Output result:
Found: 123-456-7890
Found: 987-654-3210
4. Replace matches in the string
Example
#include
#include
#include
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
Commonly used classes and types
| Name | Description |
|---|---|
std::regex |
Compiled regular expression object |
std::smatch |
std::string Match result |
std::cmatch |
C-string match result (const char*) |
std::sregex_iterator |
Used for std::string match iterator for |
std::cregex_iterator |
Match iterator for C strings |
std::syntax_option_type |
Regex 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, "#") |
smatch Match result object
| members | Description | Example |
|---|---|---|
m.str() |
Returns the entire matched content | cout << m.str() |
m[i] |
Returns the i-th capture group | m[1].str() |
m.position() |
Match starting position | m.position(0) |
m.size() |
Number of capture groups | m.size() |
m.empty() |
Whether the match is empty | m.empty() |
Common regex syntax
| sign before positive numbers | Meaning | Example | ||
|---|---|---|---|---|
. |
Any character | a.c Matches abc |
||
\d |
Digit | \d+ |
||
\w |
Alphanumeric and underscore | \w+ |
||
\s |
Whitespace character | \s+ |
||
^ |
^abc |
|||
$ |
End | xyz$ |
||
+ |
One or more times | a+ |
||
* |
Zero or more times | a* |
||
? |
Zero or one time | a? |
||
{n,m} |
n to m times | \d{2,4} |
||
() |
Capture group | (ab)+ |
||
[] |
Character set | [A-Z] |
||
| ` | ` | or | `cat | dog` |
In C++ source code strings, you should write \\d instead of \d, because \ needs to be escaped.
Typical usage example
Example
#include
#include
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
;
}