本文將演示如何在Linux環(huán)境下的c++程序中運(yùn)用正則表達(dá)式。 需要確保你的編譯器支持C++11或更高版本,因?yàn)槲覀儗⑹褂?regex>庫(kù)。
以下代碼片段展示了如何匹配一個(gè)或多個(gè)數(shù)字:
#include <iostream> #include <string> #include <regex> int main() { // 正則表達(dá)式模式 std::string pattern = R"(d+)"; // 匹配一個(gè)或多個(gè)數(shù)字 // 待匹配文本 std::string text = "Hello, there are 123 apples and 456 oranges."; // 創(chuàng)建正則表達(dá)式對(duì)象 std::regex regex(pattern); // 使用std::sregex_iterator迭代匹配結(jié)果 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; }
編譯運(yùn)行該程序:
使用g++編譯器,并指定C++11標(biāo)準(zhǔn):
立即學(xué)習(xí)“C++免費(fèi)學(xué)習(xí)筆記(深入)”;
g++ -std=c++11 -o regex_example regex_example.cpp ./regex_example
輸出結(jié)果:
Found number: 123 Found number: 456 Found 2 numbers in the text.