2017-04-22 96 views
0

我在用戶提交信息後正在訪問網頁的HTML。找到一個字符串並提取出來後的字符

如果我有...

var htmlString = "This is the massive HTML string - it has lots of characters "FindStringDetails"<123789456.123456> This is a massive HTML string - " 
var findString = "FindStringDetails\"<" 

有沒有辦法,我可以提取「FindStringDetails」 <之後來給我123789456.123456號碼以合適的方式?

回答

0
import Foundation 

var htmlString = "This is the massive HTML string - it has lots of characters \"FindStringDetails\"<123789456.123456> This is a massive HTML string - " 
var findString = "FindStringDetails\"<" 

extension String { 
    func matchingStrings(regex: String) -> [[String]] { 
     guard let regex = try? NSRegularExpression(pattern: regex, options: []) else { return [] } 
     let nsString = NSString(string: self) 
     let results = regex.matches(in: self, options: [], range: NSMakeRange(0, nsString.length)) 
     return results.map { result in 
      (0..<result.numberOfRanges).map { result.range(at: $0).location != NSNotFound 
       ? nsString.substring(with: result.range(at: $0)) 
       : "" 
      } 
     } 
    } 
} 

let m = htmlString.matchingStrings(regex: "\(findString)(\\d+)\\.(\\d+)") 

print(m[0][1]) // 123789456 
print(m[0][2]) // 123456 

(代碼改編自here。)

+0

感謝您的答覆。這給了我很多值得關注的東西。 如果我試圖獲取包含數字和數字並且還包含空格的查詢。 「John3 321」我能做些什麼來將它作爲一個字符串? –

+0

tuple_cat已回答您的原始問題。你應該接受你的問題的答案,並提出一個新的問題。 – Mozahler

+0

你的意思是像'「\(findString)(\\ d +)(\\ d +)」'? (或''\(findString)(\\ d +)[\\。](\\ d +)「'與兩者匹配。) – emlai

相關問題