我正在試圖用Scala正則表達式在網頁中查找img
src
。 使用下面的代碼和模擬內容,我沒有得到任何匹配。我錯過了什麼?Scala正則表達式在網頁上查找img src
def imgSrc(content: String) = {
val src = ".*<img[\\w\\s]+src\\s*=\\s*(\"\\w+\")[\\w\\s]+/>.*".r
val formattedContent = content.replaceAll(lineSeparator, "")
(src findAllIn formattedContent).toList
}
測試用例:
"Method imgSrc" should "find src attributes of all img tags in mock web page" in {
val content = """<a href="#search" onclick="_gaq.push(['_trackPageview', '/search']);
return Manager.createHistoryAndLoad(true);">
<img src="ajaxsolr/images/centralRepository_logo.png" alt="The Central Repository" />
</a>"""
imgSrc(content) should contain("ajaxsolr/images/centralRepository_logo.png")
}
此外,它會是不錯的可以不刪除換行符匹配多輸入。我讀this和this,但不能得到它的工作。
注意:這只是一個學習練習。我知道並普遍同意不應該使用正則表達式來解析HTML。
你試試這個http://stackoverflow.com/ questions/18664997/how-can-i-use-regular-expression-to-grab-an-img-tag? – dk14
我做了,並且與下面的@ dk14答案有相同的問題。 –