首先是代码
// It's a test string
NSString* aString =
@",{id:\"bd\",name:\"ac\",latlng {lat:37.492488999999999,lng:127.014357}}";
// NSString *strRegex = @"latlng:\\ \\{(\\S*?)[^}]*\\}";
NSString *strRegex = @"latlng:\\{(\\S*?)[^}]*\\}";
NSRegularExpression* regEx = [NSRegularExpression
regularExpressionWithPattern:strRegex
options:0
error:NULL];
NSArray* matches = [regEx matchesInString:dataString
options:0
range:NSMakeRange(0,[dataString length])];
NSInteger num=0;
for(NSTextCheckingResult* i in matches) {
NSRange range = i.range;
NSUInteger index = range.location; //the index you were looking for!
//do something here
num++;
NSLog(@"%i",num);
NSLog(@"index: %d",range.location);
NSLog(@"length: %d", range.length);
NSLog(@"%@",[aString substringWithRange:range]);
}
使用测试字符串时,一切顺利。
我的问题是当我使用数据中的字符串(其大小约为 50k)时,它会变成错误...
编辑于 2012/07/19
下面是字符串发生错误
NSError *error = nil;
NSString *urlString = [NSString stringWithFormat:@"http://maps.google.co.kr?q=%@&output=json", [address stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
//#define NSKoreanEncoding 0x80000422
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:urlString]
options:kNilOptions
error:&error];
NSString *dataString = [[NSString alloc] initWithData:data
encoding:NSKoreanEncoding];
它可以匹配 10 个结果。
运行substringWithRange:range
线路时它会崩溃。
下面是错误日志。
2012-07-19 13:31:08.792 testView[6514:11c03] index: 649
2012-07-19 13:31:08.793 testView[6514:11c03] length: 46
2012-07-19 13:31:08.793 testView[6514:11c03] *** WebKit discarded an uncaught exception in the webView:shouldInsertText:replacingDOMRange:givenAction: delegate: <NSRangeException> -[__NSCFConstantString substringWithRange:]: Range or index out of bounds