正则表达式与从 C++ 中的文件加载的长字符串的任何内容都不匹配
Regex doesn't match anything for long strings loaded from file in C++
我有一个ascii编码的纯html文件。我在Visual c++ 2012中的c++子程序中加载它,并尝试从中提取一些模式。但是我发现,无论正则表达式是什么,都找不到匹配。
我尝试了cmatch和smatch程序,但它不能与从文件加载的字符串一起工作。
文件只包含ascii字符,我需要多行正则表达式支持,但该程序仅适用于分配的字符串,而不适用于从文件加载的字符串。我检查了文件中载入的文本。加载正确。问题在于正则表达式。
void findFrasi(string filename){
fstream f;
f.open(filename, fstream::in);
char* ls;
ls = (char*)malloc(1000 * 10);
f.get(ls, fileSize, char(255));
std::string s(ls);
try {
//s= "<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">";
std::smatch cm;
std::regex e ("([\s|\S]*)(http)([\s|\S]*)", std::regex::ECMAScript | std::regex::icase );
std::regex_match( s, cm, e, regex_constants::match_any );
std::cout << "matches:" << cm.size() << std::endl;
for (std::smatch::iterator it = cm.begin(); it!=cm.end(); ++it) {
std::cout << *it << std::endl;
}
} catch (std::regex_error& e) {
if (e.code() == std::regex_constants::error_badrepeat)
std::cerr << "Repeat was not preceded by a valid regular expression.n";
else std::cerr << "Some other regex exception happened.n";
}
free(ls);
f.close();
}
异常永远不会发生!我总是得到输出:matches0
顺便说一下,我也尝试了其他正则表达式脚本,如std::regex::ECMAScript,它们没有什么不同。
您可以使用sregex_iterator
获得所有匹配项。
像这样的东西(应该运行在Visual c++ 2012与Nov2012CTP):
#include <regex>
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
std::string filepath = "jonny_regex_text.txt"; // the file you provided
std::ifstream ifs(filepath.c_str(), std::ios_base::in | std::ios_base::binary);
ifs.seekg(0, std::ios_base::end);
size_t length = static_cast<size_t>(ifs.tellg());
ifs.seekg(0, std::ios_base::beg);
std::string text;
text.resize(length);
ifs.read(&text[0], length);
ifs.close();
std::string pattern(R"((http|https|ftp)://[a-zA-Z0-9-.]+.[a-zA-Z]{2,3}(:[a-zA-Z0-9]*)?/?([a-zA-Z0-9-._?,'/\+&%$#=~])*)");
std::regex r(pattern, regex::icase);
for (std::sregex_iterator it(text.begin(), text.end(), r), end_it; it != end_it; ++it)
{
std::cout << it->str() << std::endl;
}
return 0;
}
代码打印文本文件中的所有url。
相关文章:
- 按字母顺序对字符串中的字母进行排序,而无需使用内置的 sort()
- 是否有任何内置的哈希图函数来处理 c++ 中的值输入?
- 是否有任何内置函数可以检查给定的两个数字在给定整数数组中的顺序是否相同?
- C++ 中是否有任何内置阶乘函数?
- 是否有任何内置函数可以告诉编译器分支是否可预测
- 使函数接受字符串变量内的路径
- 我需要在C /C#中使用图形.我可以使用任何内置的C /C#库
- 是否有任何内置类可以处理C 中的大整数值
- c ++中是否有任何内置功能可以在计划的时间运行任务
- 是否有任何内置的 UTF 在 c++ 在窗口中
- 在VC++2010中执行任何内置的ARRAY函数
- C++:如何在不使用任何内置函数的情况下将字符串转换为整数
- 是否有任何内置的CUDA函数允许CUDA内核向主机代码报告错误?
- C++字符串流内联
- c++中比较字符串的内置函数
- 我如何在常数时间(O(1))内获得字母表(1-26)中字符的数值/位置,而不使用任何内置方法或函数
- 有没有一种方法可以在结构中从字符串文本内联定义和初始化字符串数组
- C++中的任何内置哈希方法
- c++库中的任何内置夹子方法
- 如何将字符串向量内爆为字符串(优雅的方式)