本文將演示如何在Linux環境下的c++程序中運用正則表達式。 需要確保你的編譯器支持C++11或更高版本,因為我們將使用
以下代碼片段展示了如何匹配一個或多個數字:
#include <iostream> #include <string> #include <regex> int main() { // 正則表達式模式 std::string pattern = R"(d+)"; // 匹配一個或多個數字 // 待匹配文本 std::string text = "Hello, there are 123 apples and 456 oranges."; // 創建正則表達式對象 std::regex regex(pattern); // 使用std::sregex_iterator迭代匹配結果 auto words_begin = std::sregex_iterator(text.begin(), text.end(), regex); auto words_end = std::sregex_iterator(); int count = 0; for (auto it = words_begin; it != words_end; ++it) { std::smatch match = *it; std::cout << "Found number: " << match.str() << std::endl; count++; } std::cout << "Found " << count << " numbers in the text." << std::endl; return 0; }
編譯運行該程序:
使用g++編譯器,并指定C++11標準:
立即學習“C++免費學習筆記(深入)”;
g++ -std=c++11 -o regex_example regex_example.cpp ./regex_example
輸出結果:
Found number: 123 Found number: 456 Found 2 numbers in the text.