C++的正则表达式使用
举个例子:
1 #include <iostream> 2 #include <fstream> 3 #include <regex> 4 #include <string> 5 #include <vector> 6 7 // 读取文件内容 8 std::string readFile(const std::string& filePath) { 9 std::ifstream file(filePath); 10 if (!file.is_open()) { 11 std::cerr << "Failed to open file: " << filePath << std::endl; 12 return ""; 13 } 14 15 std::string content((std::istreambuf_iterator<char>(file)), 16 std::istreambuf_iterator<char>()); 17 file.close(); 18 return content; 19 } 20 21 // 匹配正则表达式 22 bool matchText(const std::string& text, const std::vector<std::string>& patterns) { 23 for (const auto& pattern : patterns) { 24 std::regex reg(pattern); 25 if (std::regex_search(text, reg)) { 26 std::cout << "Matched pattern: " << pattern << std::endl; 27 return true; 28 } 29 } 30 std::cout << "No match found." << std::endl; 31 return false; 32 } 33 34 int main(int argc, char* argv[]) { 35 if (argc < 2) { 36 std::cerr << "Usage: " << argv[0] << " <file_path>" << std::endl; 37 return 1; 38 } 39 40 std::string filePath = argv[1]; 41 42 // 将正则表达式模式放入vector 43 std::vector<std::string> patterns = { 44 "cat", 45 "fox", 46 "dog" 47 }; 48 49 // 读取文件内容 50 std::string content = readFile(filePath); 51 if (content.empty()) { 52 return 1; 53 } 54 55 // 进行匹配 56 matchText(content, patterns); 57 58 return 0; 59 }