亚洲国产第一_开心网五月色综合亚洲_日本一级特黄特色大片免费观看_久久久久久久久久免观看

Hello! 歡迎來到小浪云!


C++ Linux中如何使用正則表達式


avatar
小浪云 2025-02-26 116

C++ Linux中如何使用正則表達式

本文將演示如何在Linux環(huán)境下的c++程序中運用正則表達式。 需要確保你的編譯器支持C++11或更高版本,因為我們將使用庫。

以下代碼片段展示了如何匹配一個或多個數(shù)字:

#include <iostream> #include <string> #include <regex>  int main() {     // 正則表達式模式     std::string pattern = R"(d+)"; // 匹配一個或多個數(shù)字      // 待匹配文本     std::string text = "Hello, there are 123 apples and 456 oranges.";      // 創(chuàng)建正則表達式對象     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; }

編譯運行該程序:

使用g++編譯器,并指定C++11標(biāo)準(zhǔn):

立即學(xué)習(xí)C++免費學(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.

庫功能強大,支持多種正則表達式操作,例如字符串替換和分割。 更多細節(jié)請參考C++標(biāo)準(zhǔn)庫文檔。

相關(guān)閱讀