看板 MacDev 關於我們 聯絡資訊
Dear 前輩好,小弟日前須使用到正規表達式於iphone上 由於沒有在iphone上使用過Regex,所以開始尋找資料 一開始,小弟看到網路上的資料都是使用RegexKitLite來做 小弟試了一下,發現之前在VC++ or c#上用的Regex無法正確擷取所要的字串 查了一下文件,發現iOS sdk有提供NSRegularExpression功能可以使用 但是小小的測試一下,還是無法抓取想要的資料 以下是小弟的程式碼,懇請各位前輩協助,為何無法抓去網頁原始碼的一段資料? 測是半天都沒用...很灰心...T_T 請前被給予協助,謝謝前輩^^ NSError* error; NSData *htmlData = [[NSString stringWithContentsOfURL:[NSURL URLWithString: @"http://www.cwb.gov.tw/V7/"] encoding:NSUTF8StringEncoding error:&error] dataUsingEncoding:NSUTF8StringEncoding]; NSString *responseString = [[NSString alloc] initWithData:htmlData encoding:NSUTF8StringEncoding]; NSLog(@"%@",responseString); NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern: @"<div class=\"headline\">.+?</div>" options:NSRegularExpressionCaseInsensitive error:&error]; if (regex != nil) { NSTextCheckingResult *firstMatch=[regex firstMatchInString:responseString options:0 range:NSMakeRange(0, [responseString length])]; if (firstMatch) { NSRange resultRange = [firstMatch rangeAtIndex:0]; NSString *result=[responseString substringWithRange:resultRange]; NSLog(@"%@",result); } } -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 219.71.36.222
popcorny:你少了NSRegularExpressionDotMatchesLineSeparators 02/10 09:49
popcorny:還有parse html最好用xpath, regular expression不適合 02/10 09:50
popcorny:去google找"ios xpath html"試試看 02/10 09:50
chengreg:謝謝大大指導 02/10 10:08