1
我需要從一個帶有Post請求的網站返回的字符串中提取數據,並且我正在使用SwiftSoup庫解析數據。我選擇使用CSS選擇器列表項:使用正則表達式查找和替換字符串
let iconsList: Element = try doc.select("ul.icons-list").first()!
返回HTML這樣的:
<ul class="icons-list">
<li><strong>Label 1:</strong> Value 1 (Some text) </li>
<li><strong>Label 2:</strong> Value 2</li>
<li><strong>Label 3:</strong> Value 3</li>
<li><strong>Label 4:</strong> Value 4 </li>
<li><strong>Label 5:</strong> Value 5</li>
</ul>
現在我需要提取裏面陣列標籤和值和商店或可能不同的變量。我曾嘗試正則表達式像(沒有工作,也許錯的正則表達式):
let result = "This <strong>Needs to be removed</strong> is my string"
let regex = try! NSRegularExpression(pattern: "<strong>(.*)</strong>", options: .caseInsensitive)
var newStr = regex.stringByReplacingMatches(in: result, options: [], range: NSRange(0..<str.utf16.count), withTemplate: "")
print(newStr)
而且還試圖SwiftSoup選擇,如:
var labelFirst = try doc.select("ul.icons-list li:nth-child(1)")
但它也返回HTML結果。所以,我需要在這兩種情況下使用正則表達式。如何做到這一點?
另一個問題: 當我選擇選擇圖標列表類使用SwiftSoup「。選擇」選擇器。如果有任何異常,那我該如何處理?目前,我有這個代碼,但它不起作用。而如果我想處理這個塊內的多個try塊呢?
do{
let doc: Document = try SwiftSoup.parse(responseString!)
let iconsList: Element = try doc.select("ul.icons-list").first()!
print(iconsList)
}catch Exception.Error(_, let message){
print("icons list not found "+message)
}catch{
print("error")
}
在第一種情況下,您可以嘗試使用'「(?s)(。*?)」'並替換爲「$ 1」。 –
謝謝,但沒有奏效! :( –