在Ubuntu上使用C++進行正則表達式操作,你需要包含<regex>
頭文件。以下是一個簡單的示例,展示了如何使用C++的正則表達式庫:
#include <iostream>
#include <string>
#include <regex>
int main() {
// 要匹配的文本
std::string text = "Hello, my name is John Doe and I am 30 years old.";
// 正則表達式模式
std::regex pattern(R"((\w+)\s(\w+))"); // 匹配兩個單詞,中間有一個空格
// 使用std::sregex_iterator進行迭代匹配
auto words_begin = std::sregex_iterator(text.begin(), text.end(), pattern);
auto words_end = std::sregex_iterator();
std::cout << "Found " << std::distance(words_begin, words_end) << " words:" << std::endl;
for (std::sregex_iterator i = words_begin; i != words_end; ++i) {
std::smatch match = *i;
std::string match_str = match.str();
std::cout << match_str << std::endl;
}
return 0;
}
要編譯這個程序,請在終端中運行以下命令:
g++ -o regex_example regex_example.cpp
然后運行生成的可執行文件:
./regex_example
這個示例將輸出:
Found 4 words:
Hello my
my name
name is
is John
John Doe
Doe and
and I
I am
am 30
30 years
years old
你可以根據需要修改正則表達式模式以匹配不同的文本。