如何搜索txt文件以获取正则
How to search a txt file for regex?
我正在尝试使用REGEX以HTML格式输出文本文件中的电子邮件地址数,我可以打开文件并读取文件,但我不确定如何使用正则搜索文件以获取正则模式。
更新:好的,我使用了一个测试文本文件,但在以HTML格式的实际文本文件上工作,它不输出电话号码,但没有输出电子邮件地址的数量。
int _tmain(int argc, _TCHAR* argv[])
{
ifstream htmlText;
string line;
string eduEmail = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.+-]+.edu$";
string nonEduEmail = "^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.+-]+.com$";
string phoneNumbers = "[[:digit:]]{2}-[[:digit:]]{3}-[[:digit:]]{4}";
int eduEmails = 0;
int nonEduEmails = 0;
int num_phoneNumbers = 0;
htmlText.open("ltudirectory.txt");
if (htmlText.good())
{
while (getline(htmlText, line))
{
cout << line << endl;
regex r_edu(eduEmail); //the pattern to search for edu emails
regex r_com(nonEduEmail); //the pattern to search for .com emails
regex r_phoneNumbers(phoneNumbers); //the pattern to search for .com emails
bool eduEmail_match = regex_search(line, r_edu);
bool nonEmail_match = regex_search(line, r_com);
bool phoneNumber_match = regex_search(line, r_phoneNumbers);
if (eduEmail_match)
{
++eduEmails;
}
if (nonEmail_match)
{
++nonEduEmails;
}
if (phoneNumber_match)
{
++num_phoneNumbers;
}
}
}
htmlText.close();
cout << "Emails ending with .edu : " << eduEmails << endl;
cout << "Emails ending with .com : " << nonEduEmails << endl;
cout << "Number of Phone Numbers: " << num_phoneNumbers << endl;
system("pause");
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
ifstream htmlText;
string line;
string eduEmail = "(\w+)(\.|_)?(\w*)@(\w+)(\.(\w+))+";
int testNum = 0;
list<string> l;
htmlText.open("ltudirectory.txt");
if (htmlText.good())
{
while (getline(htmlText, line))
{
regex e(eduEmail); // the pattern
bool match = regex_search(line, e);
if (match) {
++testNum;
}
}
}
htmlText.close();
system("pause");
return 0;
}
相关文章:
- C++ - 忽略并从其他文件获取数据
- 为什么从文件获取图标时应用程序有时会崩溃?
- 如何在 c++ 窗口中将参数和返回的退出值传递到批处理文件/从批处理文件获取返回的退出值
- Qt .pro 文件获取 Qtkit 名称
- 提升属性树:如何使用xml文件获取子树的子级
- 从C 中的二进制文件获取整数值时
- 如何在Windows上绕过主机文件获取真实的IP地址
- 如何使用 CPP/C# 从 VHDX 文件获取文件(或文件系统)
- 从读取到对象指针数组的文件获取段错误
- 是否可以从IOS项目中的cpp文件获取文件路径
- 将数据从头文件获取到源文件中的非成员函数中
- 从两个不同的文件获取输入时,输入会发生变化
- 从文件 C++ 获取整数
- 通过在 C++ 中使用发布模式二进制文件获取崩溃原因
- C++ 将值从文件获取到数组中
- 使用HTTP上载文件.获取错误:-HttpSendReuest 12005
- 正在从外部文件获取输入
- 读/写同一个文件(获取gmon.out)
- 从二进制文件获取输入时发生访问冲突错误
- 从特定文件获取函数指针