2015-06-11 19 views
4

我有一個巨大的HTML,但在某個級別有10塊article元素。我需要主題。查找iOS中的所有HTML同級元素

<article class="box-product-big box-product-full clearfix" > 
    <div class="list-left"> 

     <div class="cover"> 
      <a id="book_cover_3100529" href="/film/fritz_lang.m-egy-varos-keresi-a-gyilkost-dvd.html"> 
                  <img src="http://s06.static.libri.hu/cover/d4/3/1090228_3.jpg" alt="Fritz Lang - M- Egy város keresi a gyilkost - DVD"/> 
               </a> 
           </div> 
     <div class="desc"> 
      <a class="book-title" href="/film/fritz_lang.m-egy-varos-keresi-a-gyilkost-dvd.html"> 

..

</article> 

下面是關於DOM:

enter image description here

用下面的方式我試圖讓他們,但零片回:

var error: NSError? 
let pattern = "<article class=\"box-product-big box-product-full clearfix\">[\\S\\s]*?</article>" 
var regex = NSRegularExpression(pattern: pattern, options: NSRegularExpressionOptions.CaseInsensitive, error: &error)! 
if error != nil { 
    println(error) 
} 
let a = regex.matchesInString(str, options: NSMatchingOptions.ReportCompletion, range: NSMakeRange(0, count(str))) 

任何想法有什麼不對?

數據來自這裏:http://www.libri.hu/talalati_lista/?text=m


我試着用不同的轉義,但得到一個錯誤:

enter image description here

String literals can include the following special characters: The escaped special characters \0 (null character), \ (backslash), \t (horizontal tab), \n (line feed), \r (carriage return), \" (double quote) and \' (single quote)

doc

+0

正斜槓不是特殊字符,也沒有在這種情況下,分隔符。沒有必要逃避它。您可能需要檢查nsregex是否需要使用分隔符和引號。否則,由於空白,正則表達式可能不會找到任何東西。可以嘗試的東西:''

[ \\小號\\秒] *?「' – sln

+0

http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags/ 1732454#1732454 – Persijn

回答

3

您使用的是向前/,這是一個特殊字符,所以你必須使用\/反斜線轉義:

let pattern = "<article class=\"box-product-big box-product-full clearfix\">[\\S\\s]*?<\/article>" 
                Escape slash with backslash ---------^ 

引述documentation

Regular Expression Metacharacters

Characters that must be quoted to be treated as literals are * ? + [ () { }^$ | \ . /

enter image description here

順便說一句,那麼您可以縮短正則表達式是這樣的:

<article[\S\s]*?<\/article> 

代碼

var error: NSError? 
let pattern = "<article[\\S\\s]*?<\/article>" 
var regex = NSRegularExpression(pattern: pattern, options: NSRegularExpressionOptions.CaseInsensitive, error: &error)! 
if error != nil { 
    println(error) 
} 
let a = regex.matchesInString(str, options: NSMatchingOptions.ReportCompletion, range: NSMakeRange(0, count(str))) 

此外,您還可以使用捕獲組捕獲內容:

(<article[\S\s]*?<\/article>) 
+0

@亞諾什嘗試使用兩個反斜線'\\ /',讓我知道 –

+0

我嘗試了所有你的建議,排出你提到是不是根據文檔,但縮短和離開了'類= ..'部分幫助,即使沒有括號 –

+0

@János太棒了,很高興能夠幫助至少:) –

相關問題