溫馨提示×

C++在Ubuntu上如何使用正則表達式

小樊
51
2025-07-10 06:26:48
欄目: 編程語言

在 Ubuntu 上使用 C++ 正則表達式庫非常簡單,因為這個庫已經作為 C++ 標準庫的一部分被包含進來。C++11 引入了 <regex> 頭文件,提供了對正則表達式的支持。下面是一個簡單的例子,演示了如何在 Ubuntu 上使用 C++ 和正則表達式:

  1. 首先,確保你的編譯器支持 C++11 或更高版本。在編譯時,你需要添加 -std=c++11-std=c++14-std=c++17 等選項來啟用相應的標準。例如,使用 g++ 編譯器:
g++ -std=c++11 your_file.cpp -o your_program
  1. 創建一個名為 your_file.cpp 的 C++ 源文件,并在其中編寫以下代碼:
#include <iostream>
#include <regex>
#include <string>

int main() {
    std::string text = "Hello, my email is example@example.com and my phone number is 123-456-7890.";
    std::regex email_regex(R"((\w+@\w+\.\w+))");
    std::regex phone_regex(R"((\d{3}-\d{3}-\d{4}))");

    std::smatch matches;

    if (std::regex_search(text, matches, email_regex)) {
        std::cout << "Email found: " << matches[0] << std::endl;
    } else {
        std::cout << "Email not found." << std::endl;
    }

    if (std::regex_search(text, matches, phone_regex)) {
        std::cout << "Phone number found: " << matches[0] << std::endl;
    } else {
        std::cout << "Phone number not found." << std::endl;
    }

    return 0;
}

這個程序會在給定的文本中查找電子郵件地址和電話號碼,并將它們打印出來。

  1. 使用 g++ 編譯器編譯你的程序:
g++ -std=c++11 your_file.cpp -o your_program
  1. 運行編譯后的程序:
./your_program

你應該會看到以下輸出:

Email found: example@example.com
Phone number found: 123-456-7890

這就是在 Ubuntu 上使用 C++ 正則表達式的基本方法。你可以根據需要修改正則表達式以匹配不同的模式。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女