目录
std::regex
是 C++11 引入的正则表达式库,它允许在字符串中进行模式匹配。正则表达式是一种强大的字符串匹配工具,允许你使用模式来描述你感兴趣的字符串集。
以下是一些常见的 std::regex
的用法,以及如何在 C++ 中使用它们:
基本用法
-
构造正则表达式对象:
std::regex pattern("hello");
-
使用正则表达式进行匹配:
std::string text = "hello world"; if (std::regex_search(text, pattern)) { std::cout << "Match found!" << std::endl; } else { std::cout << "No match found." << std::endl; }
匹配结果
std::smatch
类型用于保存匹配结果,你可以使用它来获取匹配的子串。
std::regex pattern("\\d+"); // 匹配一个或多个数字
std::string text = "The price is $42.";
std::smatch match;
if (std::regex_search(text, match, pattern)) {
std::cout << "Match found: " << match.str() << std::endl;
} else {
std::cout << "No match found." << std::endl;
}
迭代器
你还可以使用 std::sregex_iterator
迭代器来遍历匹配的所有结果:
std::regex pattern("\\b\\w+\\b"); // 匹配单词
std::string text = "This is a sample text.";
std::sregex_iterator iter(text.begin(), text.end(), pattern);
std::sregex_iterator end;
while (iter != end) {
std::cout << "Match found: " << iter->str() << std::endl;
++iter;
}
替换
使用 std::regex_replace
进行字符串替换:
std::regex pattern("\\d+"); // 匹配一个或多个数字
std::string text = "The price is $42.";
std::string result = std::regex_replace(text, pattern, "[NUMBER]");
std::cout << "Result: " << result << std::endl;
regex小试牛刀 ,提取文件中所有https链接
#include <iostream>
#include <fstream>
#include <regex>
#include <string>
// Function to extract HTTPS links from a given text
std::vector<std::string> extractHttpsLinks(const std::string& text) {
std::vector<std::string> links;
// HTTPS link regex pattern
std::regex linkRegex(R"(https:\/\/[^\s\[\]\(\)<>"',]+)");
// Iterator for matching links
std::sregex_iterator linkIterator(text.begin(), text.end(), linkRegex);
std::sregex_iterator endIterator;
// Extract matching links
while (linkIterator != endIterator) {
links.push_back(linkIterator->str());
++linkIterator;
}
return links;
}
// Function to read a file and extract HTTPS links
std::vector<std::string> extractHttpsLinksFromFile(const std::string& fileName) {
std::ifstream file(fileName);
std::string content;
if (file.is_open()) {
// Read the entire content of the file into a string
content.assign(std::istreambuf_iterator<char>(file), std::istreambuf_iterator<char>());
file.close();
} else {
std::cerr << "Unable to open file: " << fileName << std::endl;
}
// Extract HTTPS links from the file content
return extractHttpsLinks(content);
}
int main(int argc, char* argv[]) {
// Replace "your_cpp_file.cpp" with the path to your C++ file
std::string cppFileName = argv[1];
// Extract HTTPS links from the C++ file
std::vector<std::string> httpsLinks = extractHttpsLinksFromFile(cppFileName);
// Print the extracted HTTPS links
std::cout << "HTTPS links in " << cppFileName << ":" << std::endl;
for (const std::string& link : httpsLinks) {
std::cout << link << std::endl;
}
return 0;
}
这是一个简单的正则表达式介绍和使用示例。实际使用中,正则表达式可以更复杂,支持字符集、分组、量词等高级特性,以满足不同的匹配需求。请注意,正则表达式中的某些字符可能需要进行转义,例如 \
需要写作 \\
。