C++11引入了<regex>
库,它提供了正则表达式功能。这个库包含了三个主要的函数:regex_match
,regex_search
和regex_replace
。下面是它们的详解:
1. regex_match
regex_match
函数用于检查一个整个字符串是否完全匹配一个正则表达式。它返回一个布尔值,如果整个字符串完全匹配正则表达式,则返回true,否则返回false。
#include <iostream>
#include <string>
#include <regex>
int main() {
std::string s("hello");
std::regex e("\\w+"); // 匹配任何单词字符 (等价于'[a-zA-Z0-9_]')
bool match = std::regex_match(s, e);
std::cout << (match ? "matched" : "not matched") << std::endl;
return 0;
}
regex_search
regex_search
函数用于在一个字符串中搜索与正则表达式匹配的子串。如果找到匹配的子串,它返回true,否则返回false。与regex_match
不同,regex_search
不需要整个字符串都匹配正则表达式。
#include <iostream>
#include <string>
#include <regex>
int main() {
std::string s("hello world");
std::regex e("world"); // 匹配'world'
bool match = std::regex_search(s, e);
std::cout << (match ? "matched" : "not matched") << std::endl;
return 0;
}
regex_replace
regex_replace
函数用于在一个字符串中查找与正则表达式匹配的子串,并用另一个字符串替换它们。它返回替换后的字符串。如果没有找到匹配的子串,则返回原始字符串。
#include <iostream>
#include <string>
#include <regex>
int main() {
std::string s("hello world");
std::regex e("world"); // 匹配'world'
std::string replacement = "C++";
std::string result = std::regex_replace(s, e, replacement);
std::cout << result << std::endl; // 输出: hello C++
return 0;
}