Qt正则表达式获取html中img

这段代码使用正则表达式QRegExpr匹配HTML中<img>标签的src属性,并通过设置setMinimal为true确保匹配最短的匹配项。在循环中找到所有匹配项,提取出src属性的值,截取从'src='后的字符串直到下一个'',用于获取图片URL。
 QRegExp rx("<img[^>]*src[=]+[^.]*/+[^>]*>"); //匹配<img src *>
    rx.setMinimal(true);
    int pos = 0;
    while ((pos = rx.indexIn(selected_text, pos)) != -1)
    {
        pos += rx.matchedLength();

        QString str = rx.cap();
        str = str.mid(str.indexOf("src=\"") + 5);
        str = str.left(str.indexOf("\""));
    }

C++ qt 优化速度// 修复Trioptics文档使其符合XML规范: QString TriopticsParser::preprocessTriopticsForXml(const QString & html) { QString result; // 预分配内存(减少重新分配) result.reserve(html.size() + 200); // 合并步骤:查<html>位置并修复字符集 int htmlStart = html.indexOf("<html>", 0, Qt::CaseInsensitive); if (htmlStart == -1) htmlStart = 0; // 单次遍历处理多个任务 bool xmlAdded = false; // 避免重复检查 int pos = htmlStart; const int htmlSize = html.size(); while (pos < html.size()) { // 使用预编译的正则表达式 QRegularExpressionMatch tagMatch = tagRegex.match(html, pos); if (tagMatch.hasMatch()) { const int matchStart = tagMatch.capturedStart(); // 添加标签前的内容(使用QStringRef避免复制) if (matchStart > pos) { result.append(QStringRef(&html, pos, matchStart - pos)); } // 获取标签组件(转换为小写) QString selfClose = tagMatch.captured(0); QString slash = tagMatch.captured(1); QString tagName = tagMatch.captured(2).toLower(); // 特殊标签处理 if (tagName == "html" && !result.contains("<?xml")) { result.append("<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n"); } // 构建新标签 result += '<' % slash % tagName % '>'; pos = tagMatch.capturedEnd(); // 自闭合标签特殊处理 QRegularExpressionMatch selfMatch = selfClosingRegex.match(selfClose); if (selfMatch.hasMatch()) { result.replace(result.length() - 1, 1, "/>"); } } } result.replace("</link>", ""); // 移除无效闭合标签 return result;
最新发布
08-05
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值