She*_*lam 3 iphone cocoa-touch nsstring nsrange
我正在尝试检测我的字符串中的网站URL,然后做一些归属字符串,如粗体等.
我的正则表达式定义为:
static NSRegularExpression *websiteRegularExpression;
static inline NSRegularExpression * WebsiteRegularExpression() {
if (!websiteRegularExpression) {
websiteRegularExpression = [[NSRegularExpression alloc] initWithPattern:@"\b(https?|ftp|file)://[-A-Z0-9+&@#/%?=~_|!:,.;]*[A-Z0-9+&@#/%=~_|]"
options:NSRegularExpressionCaseInsensitive
error:nil];
}
return websiteRegularExpression;
}
Run Code Online (Sandbox Code Playgroud)
这是我列举的地方:
-(void)setBodyText
{
__block NSRegularExpression *regexp = nil;
bodyLabel.delegate = self;
[self.bodyLabel setText:@"http://www.google.com" afterInheritingLabelAttributesAndConfiguringWithBlock:^NSAttributedString *(NSMutableAttributedString *mutableAttributedString) {
NSRange stringRange = NSMakeRange(0, [mutableAttributedString length]);
regexp = WebsiteRegularExpression ();
NSRange nameRange = [regexp rangeOfFirstMatchInString:[mutableAttributedString string] options:0 range:stringRange];
UIFont *boldSystemFont = [UIFont boldSystemFontOfSize:18.0];
CTFontRef boldFont = CTFontCreateWithName((CFStringRef)boldSystemFont.fontName, boldSystemFont.pointSize, NULL);
if (boldFont) {
[mutableAttributedString addAttribute:(NSString *)kCTFontAttributeName value:(id)boldFont range:nameRange];
CFRelease(boldFont);
}
[mutableAttributedString replaceCharactersInRange:nameRange withString:[[[mutableAttributedString string] substringWithRange:nameRange] uppercaseString]];
return mutableAttributedString;
}];
regexp = WebsiteRegularExpression();
NSRange linkRange = [regexp rangeOfFirstMatchInString:self.bodyLabel.text options:0 range:NSMakeRange(0, [bodyLabel.text length])];
[self.bodyLabel addLinkToURL:nil withRange:linkRange];
}
Run Code Online (Sandbox Code Playgroud)
我收到错误:
*** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[NSCFString substringWithRange:]: Range or index out of bounds'
Run Code Online (Sandbox Code Playgroud)
我怎么解决?
在调用substringWithRange之前检查nameRange的内容.如果正则表达式不匹配,则rangeOfFirstMatchInString的返回值将为
{NSNotFound,0}
NSNotFound定义为NSIntegerMax,因此您可以想象为什么此值可能超出mutableAttributedString的范围.
更新评论
所以要检查substringWithRange的结果:
if (nameRange.location == NSNotFound)
// didn't match the WebsiteRegularExpression() do something else
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7768 次 |
| 最近记录: |