我正在尝试检测字符串中的网站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;
}
这是我列举的地方:
-(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];
}
我得到错误:
*** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[NSCFString substringWithRange:]: Range or index out of bounds'
我该如何解决?
最佳答案
在调用substringWithRange之前,请检查nameRange的内容。如果您的正则表达式不匹配,则rangeOfFirstMatchInString的返回值将为
{NSNotFound,0}
NSNotFound被定义为NSIntegerMax,因此您可以想象为什么此值可能超出mutableAttributedString的范围。
更新评论
所以要检查substringWithRange的结果:
if (nameRange.location == NSNotFound)
// didn't match the WebsiteRegularExpression() do something else