我想用正则表达式搜索文件,结果应该是所有匹配的字符串。
我已经编写了用于命令行执行的正则表达式,但我需要在C ++中实现它:
grep -E -o "\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,6}\b" filename.txt
我可以使用regex_search函数吗?
根据此示例here,该方法将字符串作为输入。 我是否必须自己打开并逐行阅读,或者是否有办法将文件作为参数提供,只是将结果作为返回值?
EDIT 我现在实现了正则表达式搜索,但是我没有按预期获得结果。
void readFile(fs::path filename) {
ifstream in(filename.string(), ios::in | ios::binary);
if (in) {
string content;
in.seekg(0, ios::end);
content.resize(in.tellg());
in.seekg(0, ios::beg);
in.read(&content[0], content.size());
in.close();
searchContent(content);
}
}
void searchContent(string content) {
smatch match;
regex expr("\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,6}");
while (regex_search(content, match, expr)) {
for (auto x : match)
cout << x << " ";
cout << std::endl;
content = match.suffix().str();
}
}
我的测试文件包含以下内容:
abc@gmail.com xxx
xxx xx test@yahoo.com xxx
sss a@a.to
但是我从程序得到的输出是
abc@gmail.com xxx
test@yahoo.com xxx
a@a.to
不应打印最后一个xxx
!