C++ Regex Tutorial: Pattern Matching in C++
In C++, the regex library can be used for regular expression matching. Here are some basic examples of using the regex library:
- Include the regex header file:
#include <regex>
- Create a regular expression object.
std::regex pattern("正则表达式字符串");
- Match with regular expression object:
std::string str = "待匹配字符串";
if (std::regex_match(str, pattern)) {
// 字符串与正则表达式匹配
} else {
// 字符串与正则表达式不匹配
}
- Find matches using a regular expression object.
std::string str = "待匹配字符串";
std::smatch match;
if (std::regex_search(str, match, pattern)) {
// 查找到匹配的子串
for (size_t i = 0; i < match.size(); ++i) {
std::cout << match[i] << std::endl;
}
}
- Replace matches using a regular expression object.
std::string str = "待匹配字符串";
std::string replacement = "替换字符串";
std::string result = std::regex_replace(str, pattern, replacement);
Above are some basic usages of the regex library, more complex regular expression operations can be performed based on specific needs.