2012-12-19 26 views
1
使用NSRegularExpression找到與40個字符的ID的出現在HTML

IOS使用正則表達式來找到ID在HTML

這裏我的代碼:

- (NSString *)stripOutHttp:(NSString *)string { 

NSLog(@"the page content :: %@", string); 

// Setup an NSError object to catch any failures 
NSError *error = NULL; 

// create the NSRegularExpression object and initialize it with a pattern 
// the pattern will match any http or https url, with option case insensitive 

//search for:: <input type="hidden" name="XID" value="f3f3fbafe552358d9312d1fe30670add09adc36c" /> 


NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"<input type=\"hidden\" name=\"XID\" value\"?" options:NSRegularExpressionCaseInsensitive error:&error]; // ultimo funcional 



// try /\b([a-f0-9]{40})\b/ 


// create an NSRange object using our regex object for the first match in the string 

NSRange rangeOfFirstMatch = [regex rangeOfFirstMatchInString:string options:0 range:NSMakeRange(0, [string length])]; 

// check that our NSRange object is not equal to range of NSNotFound 

if (!NSEqualRanges(rangeOfFirstMatch, NSMakeRange(NSNotFound, 0))) { 
    // Since we know that we found a match, get the substring from the parent string by using our NSRange object 

    NSString *substringForFirstMatch = [string substringWithRange:rangeOfFirstMatch]; 

    NSLog(@"Extracted data : %@",substringForFirstMatch); 

    // return the matching string 
    return substringForFirstMatch; 
} 

return NULL; 
    } 
我目前正則表達式

所以:

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"<input type=\"hidden\" name=\"XID\" value\"?" options:NSRegularExpressionCaseInsensitive error:&error]; // ultimo funcional 

我得到我所需要的部分:

Extracted data : <input type="hidden" name="XID" value 

現在我該如何獲得任何40個字符值的響應?

我試圖與

// try /\b([a-f0-9]{40})\b/ 

但不似乎瞭解如何使用它,

這是::

<input type="hidden" name="XID" value="f3f3fbafe552358d9312d1fe30670add09adc36c" /> 

非常感謝後的一種迴應IM的

+2

用HTML解析器解析HTML。這會容易得多。 – Blender

回答

1

正則表達式

<input type=\"hidden\" name=\"XID\" value=\"([a-f0-9]{40})\"[\s]*/> 

應該與輸入字符串

我不認爲這是最好的主意儘管如此,首先,你可以使用很多空間,任意空白也是可能的。 如果我是你,我會研究html解析器庫。

2

你應該考慮用html或xml解析器來解析整個事物(比如Blender說的),但就目前而言,回答你的問題將是以下幾點:

"<[^>]*id=DIVNAME.*?>(.*?)/>"