我想檢測網站的網址在我的字符串,然後做一些屬性字符串的東西一樣粗體就等問題使用NSRange:索引出界
我的正則表達式定義爲:
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'
我該如何解決?
你可以發佈你正在使用正則表達式?具體是什麼是mutableAttributedString。我的猜測在這一行中是錯誤的。 [mutableAttributedString string] substringWithRange:nameRange] uppercaseString]];您可能需要通過確保每個步驟都讓您滿意,進行調試。 – madmik3
我相信你是對的。我用正則表達式更新了我的代碼。仍然不知道如何解決... –