在Linux环境下使用C++处理正则表达式主要有两种方式:C++11标准库中的<regex>
和POSIX正则表达式函数。下面我将详细介绍这两种方法。
<regex>
C++11引入了标准正则表达式库,这是最现代和推荐的方式。
#include <iostream>
#include <regex>
#include <string>
int main() {
std::string text = "My email is example@domain.com and phone is 123-456-7890";
// 匹配电子邮件
std::regex email_pattern(R"(\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}\b)");
std::smatch email_matches;
if (std::regex_search(text, email_matches, email_pattern)) {
std::cout << "Found email: " << email_matches[0] << std::endl;
}
// 匹配电话号码
std::regex phone_pattern(R"(\b\d{3}-\d{3}-\d{4}\b)");
auto phone_begin = std::sregex_iterator(text.begin(), text.end(), phone_pattern);
auto phone_end = std::sregex_iterator();
std::cout << "Found " << std::distance(phone_begin, phone_end) << " phone numbers:\n";
for (std::sregex_iterator i = phone_begin; i != phone_end; ++i) {
std::smatch match = *i;
std::cout << match.str() << std::endl;
}
// 替换操作
std::string replaced = std::regex_replace(text, phone_pattern, "***-***-****");
std::cout << "After replacement: " << replaced << std::endl;
return 0;
}
简单匹配:
std::regex pattern("your_pattern");
bool match = std::regex_match(input_string, pattern);
搜索匹配:
std::smatch matches;
if (std::regex_search(input_string, matches, pattern)) {
// 处理匹配结果
}
迭代所有匹配:
auto begin = std::sregex_iterator(input.begin(), input.end(), pattern);
auto end = std::sregex_iterator();
for (auto i = begin; i != end; ++i) {
std::smatch match = *i;
// 处理每个匹配
}
替换匹配内容:
std::string result = std::regex_replace(input, pattern, replacement);
如果由于某些原因不能使用C++11,可以使用POSIX正则表达式函数。
#include <iostream>
#include <regex.h>
#include <string.h>
int main() {
const char* text = "Sample text with numbers 123 and 456";
regex_t regex;
int ret;
char msgbuf[100];
// 编译正则表达式
ret = regcomp(®ex, "[0-9]+", REG_EXTENDED);
if (ret) {
regerror(ret, ®ex, msgbuf, sizeof(msgbuf));
std::cerr << "Regex compile failed: " << msgbuf << std::endl;
return 1;
}
// 执行匹配
regmatch_t matches[10];
const char* p = text;
while (1) {
ret = regexec(®ex, p, 10, matches, 0);
if (ret == REG_NOMATCH) break;
if (ret) {
regerror(ret, ®ex, msgbuf, sizeof(msgbuf));
std::cerr << "Regex match failed: " << msgbuf << std::endl;
break;
}
// 输出匹配结果
int start = matches[0].rm_so;
int end = matches[0].rm_eo;
std::cout << "Found match: " << std::string(p + start, p + end) << std::endl;
p += matches[0].rm_eo; // 移动到匹配结束位置
}
regfree(®ex); // 释放正则表达式
return 0;
}
regcomp()
regexec()
regfree()
regerror()
特性 | C++11 <regex> |
POSIX regex |
---|---|---|
易用性 | 高 | 低 |
功能 | 丰富 | 基本 |
性能 | 一般 | 较高 |
可移植性 | 跨平台 | 主要在Unix-like系统 |
标准 | C++标准 | POSIX标准 |
推荐程度 | 推荐 | 仅限需要兼容旧系统时 |
使用C++11正则表达式时,需要确保编译器支持C++11标准:
g++ -std=c++11 your_program.cpp -o your_program
对于POSIX正则表达式,需要链接相应的库:
g++ your_program.cpp -o your_program
对于现代C++开发,强烈推荐使用C++11标准库中的<regex>
,它提供了更简洁、更安全的接口。只有在需要兼容旧系统或特殊需求时,才考虑使用POSIX正则表达式函数。