作者chengreg (想重回校园的工程师)
看板MacDev
标题[问题] NSRegularExpress表达式失效一问
时间Thu Feb 9 22:29:59 2012
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
1F:推 popcorny:你少了NSRegularExpressionDotMatchesLineSeparators 02/10 09:49
2F:→ popcorny:还有parse html最好用xpath, regular expression不适合 02/10 09:50
3F:→ popcorny:去google找"ios xpath html"试试看 02/10 09:50
4F:→ chengreg:谢谢大大指导 02/10 10:08