Regular expressions library
cppreference.com
< cpp
<regex> . |
, , , .regex
Almost all operations with regexes can be characterized by operating on several of the following objects:
- . . 2 , std::string ..
- . . . std::basic_regex , . syntax_option_type .
- (Matched array). std::match_results , .
- . . match_flag_type
.
(C++11) |
regular expression object (class template) |
(C++11) |
identifies the sequence of characters matched by a sub-expression (class template) |
(C++11) |
identifies one regular expression match, including all sub-expression matches (class template) |
regex .
(C++11) |
attempts to match a regular expression to an entire character sequence (function template) |
(C++11) |
attempts to match a regular expression to any part of a character sequence (function template) |
(C++11) |
replaces occurrences of a regular expression with formatted replacement text (function template) |
regex .
(C++11) |
iterates through all regex matches within a character sequence (class template) |
(C++11) |
iterates through the specified sub-expressions within all regex matches in a given string or through unmatched substrings (class template) |
.
(C++11) |
reports errors generated by the regular expressions library (class) |
regex regex .
(C++11) |
provides metainformation about a character type, required by the regex library (class template) |
Constants
Defined in namespace
std::regex_constants | |
(C++11) |
general options controlling regex behavior (typedef) |
(C++11) |
options specific to matching (typedef) |
(C++11) |
describes different types of matching errors (typedef) |
Example
#include <iostream>
#include <iterator>
#include <string>
#include <regex>
int main()
{
std::string s = "Some people, when confronted with a problem, think "
"\"I know, I'll use regular expressions.\" "
"Now they have two problems.";
std::regex self_regex("REGULAR EXPRESSIONS",
std::regex_constants::ECMAScript | std::regex_constants::icase);
if (std::regex_search(s, self_regex)) {
std::cout << "Text contains the phrase 'regular expressions'\n";
}
std::regex word_regex("(\\S+)");
auto words_begin =
std::sregex_iterator(s.begin(), s.end(), word_regex);
auto words_end = std::sregex_iterator();
std::cout << "Found "
<< std::distance(words_begin, words_end)
<< " words\n";
const int N = 6;
std::cout << "Words greater than " << N << " characters:\n";
for (std::sregex_iterator i = words_begin; i != words_end; ++i) {
std::smatch match = *i;
std::string match_str = match.str();
if (match_str.size() > N) {
std::cout << " " << match_str << '\n';
}
}
std::regex long_word_regex("(\\w{7,})");
std::string new_s = std::regex_replace(s, long_word_regex, "[$&]");
std::cout << new_s << '\n';
}
Output:
Text contains the phrase 'regular expressions'
Found 19 words
Words greater than 6 characters:
people,
confronted
problem,
regular
expressions."
problems.
Some people, when [confronted] with a [problem], think
"I know, I'll use [regular] [expressions]." Now they have two [problems].