[問題] NSRegularExpress表達式失效一問

看板MacDev作者 (想重回校園的工程師)時間13年前 (2012/02/09 22:30), 編輯推噓1(103)
留言4則, 2人參與, 最新討論串1/1
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

02/10 09:49, , 1F
你少了NSRegularExpressionDotMatchesLineSeparators
02/10 09:49, 1F

02/10 09:50, , 2F
還有parse html最好用xpath, regular expression不適合
02/10 09:50, 2F

02/10 09:50, , 3F
去google找"ios xpath html"試試看
02/10 09:50, 3F

02/10 10:08, , 4F
謝謝大大指導
02/10 10:08, 4F
文章代碼(AID): #1FCzXfez (MacDev)
文章代碼(AID): #1FCzXfez (MacDev)