まず最初に、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="..."
それは機能しますが、正しい方法で機能させることができないからです。また、標準化するためにいくつかのものを追加しました