【问题标题】:How to get the src of an image tag using QRegExp and QString如何使用 QRegExp 和 QString 获取图像标签的 src
【发布时间】:2018-07-09 19:09:54
【问题描述】:

所以我的应用程序中有一个字符串,其中包含一个 html img 标签

<img src="imagsource.jpg" width="imageWidth" />

现在我想在两个不同的字符串中提取图像标签及其src 属性。所以我试图做的是:

QRegExp imageRegex("\\<img[^\\>]*src\\s*=\\s*\"([^\"]*)\"[^\\>]*\\>", Qt::CaseInsensitive);

int a = imageRegex.indexIn(description);
int b = a + imageRegex.matchedLength();

QString imgTag = description.mid(a,b); // this kind of works but doesn't return the img tag properly (extra information is included)

// how to obtain the "src" attribute, I have tried this: src\s*=\s*\"(.+?)" but it doesn't work
QString imgSrc = ??

我尝试查看有关如何使用正则表达式从其他字符串中提取字符串的其他帖子,我尝试在 QRegExp 中使用相同的模式,但它们似乎没有给出正确的结果。

【问题讨论】:

标签: regex qt qstring qregexp


【解决方案1】:

试试看

&lt;img(?=\s)(?=(?:[^&gt;"']|"[^"]*"|'[^']*')*?\ssrc\s*=\s*(?:(['"])([\S\s]*?)\1))\s+(?:"[\S\s]*?"|'[\S\s]*?'|[^&gt;]*?)+&gt;

https://regex101.com/r/qaQPPU/1

其中,src 值在捕获组 2 中。

可读的正则表达式

 < img                  # Begin img tag
 (?= \s )
 (?=                    # Asserttion (a pseudo atomic group)
      (?: [^>"'] | " [^"]* " | ' [^']* ' )*?
      \s src \s* = \s*       # src Attribute
      (?:
           ( ['"] )               # (1), Quote
           ( [\S\s]*? )           # (2), src Value
           \1 
      )
 )
                        # Have the value, just match the rest of tag
 \s+ 
 (?: " [\S\s]*? " | ' [\S\s]*? ' | [^>]*? )+

 >                      # End tag

更新

使用 Qt 5 或更高版本(5.11 ?)。

使用那个版本更像是 Perl 正则表达式。

参考:http://doc.qt.io/qt-5/qregularexpression.html

例子:

QRegularExpression re("<img(?=\\s)(?=(?:[^>\"']|\"[^\"]*\"|'[^']*')*?\\ssrc\\s*=\\s*(?:(['\"])([\\S\\s]*?)\\1))\\s+(?:\"[\\S\\s]*?\"|'[\\S\\s]*?'|[^>]*?)+>");
QRegularExpressionMatch match = re.match("<img src=\"imagsource.jpg\"     width=\"imageWidth\" />", 1);
if (match.hasMatch()) {
    QString matched = match.captured(2); // matched -> imagsource.jpg
    // ...
}

【讨论】:

  • @sin 我在输入img 标记结构时犯了一个错误,但我已经更改了它。您的正则表达式似乎不起作用。我的代码是:QRegExp imageRegex("&lt;img(?=\s)(?=(?:[^&gt;\"']|\"[^\"]*\"|'[^']*')*?\ssrc\s*=\s*(?:(['\"])([\S\s]*?)\1))\s+(?:\"[\S\s]*?\"|'[\S\s]*?'|[^&gt;]*?)+&gt;", Qt::CaseInsensitive);
【解决方案2】:

你可以用这个:

<img.*src=(?:"(.*?)"|'(.*?)').*>

https://regex101.com/r/qaQPPU/3

它将捕获整个匹配中的整个标签,然后是第一组中src标签的内容。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多