0

まず最初に、HTML に正規表現を使用するのは良くない考えであることを理解しているとだけ言いたいと思います。タグ情報を取得するために使用しているだけ<img>なので、ネストなどは気にしません。

そうは言ってもsrc、Web ページ内のすべての画像の URL を取得しようとしています。しかし、私は最初の結果しか得ていないようです。それは私の正規表現ですか、それとも私が使用している方法ですか? 私の正規表現スキルは少しさびているので、明らかな何かが欠けている可能性があります。

QRegExp imgTagRegex("(<img.*>)+", Qt::CaseInsensitive); //Grab the entire <img> tag
imgTagRegex.setMinimal(true);
imgTagRegex.indexIn(pDocument);
QStringList imgTagList = imgTagRegex.capturedTexts();
imgTagList.removeFirst();   //the first is always the total captured text

foreach (QString imgTag, imgTagList) //now we want to get the source URL
{
    QRegExp urlRegex("src=\"(.*)\"", Qt::CaseInsensitive);
    urlRegex.setMinimal(true);
    urlRegex.indexIn(imgTag);
    QStringList resultList = urlRegex.capturedTexts();
    resultList.removeFirst();
    imageUrls.append(resultList.first());
}

foreachループに到達するまでに、imgTagList文字列は 1 つしか含まれていません。「古代エジプトの猫」ウィキペディアのページには、次のものが含まれます。

<img alt="" src="//upload.wikimedia.org/wikipedia/commons/thumb/1/13/Egypte_louvre_058.jpg/220px-Egypte_louvre_058.jpg" width="220" height="407" class="thumbimage" srcset="//upload.wikimedia.org/wikipedia/commons/thumb/1/13/Egypte_louvre_058.jpg/330px-Egypte_louvre_058.jpg 1.5x, //upload.wikimedia.org/wikipedia/commons/1/13/Egypte_louvre_058.jpg 2x" />

どちらが欲しいのですが、ページにもっと多くの画像タグがあることは知っています...なぜ最初のものだけが戻ってくるのでしょうか?


アップデート

Sebastian Lange の助けを借りて、ここまでたどり着くことができました。

QRegExp imgTagRegex("<img.*src=\"(.*)\".*>", Qt::CaseInsensitive);
imgTagRegex.setMinimal(true);
QStringList urlMatches;
QStringList imgMatches;
int offset = 0;
while(offset >= 0)
{
    offset = imgTagRegex.indexIn(pDocument, offset);
    offset += imgTagRegex.matchedLength();

    QString imgTag = imgTagRegex.cap(0);
    if (!imgTag.isEmpty())
        imgMatches.append(imgTag); // Should hold complete img tag

    QString url = imgTagRegex.cap(1);
    if (!url.isEmpty())
    {
        url = url.split("\"").first(); //ehhh....
        if (!urlMatches.contains(url))
            urlMatches.append(url); // Should hold only src property
    }
}

最後のsplitは、タグ内の非 src 要素を取り除くハックな方法です。これは、セグメント<img>内のデータだけを取得できないように見えるためです。src="..."それは機能しますが、正しい方法で機能させることができないからです。また、標準化するためにいくつかのものを追加しました

4

1 に答える 1

1

通常、QRegExp は 1 つの一致のみを返します。リストcapturedTexts()は、この1つの一致のすべてのキャプチャを提供します!1 つの正規表現ステートメントに複数のキャプチャ ブラケットを含めることができます。問題を解決するには、次のようなことを行う必要があります。

QRegExp imgTagRegex("\\<img[^\\>]*src\\s*=\\s*\"([^\"]*)\"[^\\>]*\\>", Qt::CaseInsensitive);
imgTagRegex.setMinimal(true);
QStringList urlmatches;
QStringList imgmatches;
int offset = 0;
while( (offset = imgTagRegex.indexIn(pDocument, offset)) != -1){
    offset += imgTagRegex.matchedLength();
    imgmatches.append(imgTagRegex.cap(0)); // Should hold complete img tag
    urlmatches.append(imgTagRegex.cap(1)); // Should hold only src property
}

編集: キャプチャ RegExpression を EDIT2 に変更"\\<img[^\\>]*src=\"([^\"]*)\"[^\\>]*\\>" : src 文字列に可能なスペースを追加:"\\<img[^\\>]*src\\s*=\\s*\"([^\"]*)\"[^\\>]*\\>"

于 2013-07-17T05:53:22.050 に答える