所以我在许多不同的文本文件中都有电子邮件,我需要从所述文件中提取它们,这些文件在布局上不一致。我正在使用Boost::Regex
和Boost::File-system
尝试阅读它们,然后提取电子邮件地址。但是它似乎没有找到或拔出电子邮件。它可以匹配简单的单词,如email
或字母a
。但实际读出文件似乎有问题。
最小的例子如下(不包括):
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <boost/regex.hpp>
#include <boost/foreach.hpp>
#include <boost/filesystem.hpp>
namespace fs = boost::filesystem; // File system is namespace.
int main() {
boost::regex pattern("\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}\b"); // Email regex to match.
boost::smatch result;
fs::path targetDir(boost::filesystem::current_path()); // Look in this folder.
fs::directory_iterator it(targetDir), eod; // Iterate over all the files in said directory.
std::string line;
BOOST_FOREACH(fs::path const &p, std::make_pair(it, eod)) { // Actual iteration.
if (fs::is_regular_file(p)) { // What this does is checks if it's a normal file.
std::ifstream infile(p.string()); // Read file line by line.
if (p.string().substr(p.string().length() - 3) != "txt") {
continue; // Skip to next file if not text file.
}
while (std::getline(infile, line)) {
bool isMatchFound = boost::regex_search(line, result, pattern);
if (isMatchFound)
{
for (unsigned int i = 0; i < result.size(); i++)
{
std::cout << result[i] << std::endl;
}
}
}
infile.close();
}
}
return 0;
}
我不确定为什么它不起作用:电子邮件的样本如下:
"radafwair@dasfsn.com","S"
"eliseoaafwafwlcon@mafwsn.com","R"
jjafwpawwafa2@csaot.net<br>
电子邮件可以在文本文件中的其他各种方式,如何使这个正则表达式匹配?
答案 0 :(得分:3)
正则表达式存在缺陷。 \b
表示其他内容:
此外,\.
是非法转义序列,因此您的编译器应该已经发出警告。 (您需要\\.
)
最后,我认为\b
是与Perl兼容的正则表达式。哦,你不只是想要大写的电子邮件,对吧。所以我们来解决它:
boost::regex pattern("\\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,}\\b",
boost::regex_constants::perl | boost::regex_constants::icase); // Email regex to match.
使用rfc822解析器库可能会好一点:)
这是一段经过清理的代码:
#include <boost/filesystem.hpp>
#include <boost/range/iterator_range.hpp>
#include <boost/regex.hpp>
#include <fstream>
#include <iostream>
namespace fs = boost::filesystem;
int main() {
boost::regex pattern("\\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,}\\b",
boost::regex_constants::perl | boost::regex_constants::icase); // Email regex to match.
boost::smatch result;
std::string line;
for (fs::path p : boost::make_iterator_range(fs::directory_iterator("."), {})) {
if (!fs::is_regular_file(p) || p.extension() != ".txt")
continue;
std::cerr << "Reading " << p << "\n";
std::ifstream infile(p.string()); // Read file line by line
while (std::getline(infile, line)) {
if (boost::regex_search(line, result, pattern)) {
std::cout << "\t" << result.str() << "\n";
}
}
}
}
注意:
extension()
访问函数str()
值在我的测试文件夹上打印(包括stderr):
Reading "./input.txt"
radafwair@dasfsn.com
eliseoaafwafwlcon@mafwsn.com
jjafwpawwafa2@csaot.net
Reading "./output.txt"
Reading "./big.txt"
Reading "./CMakeLists.txt"
Reading "./CMakeCache.txt"