【发布时间】:2011-06-29 02:57:14
【问题描述】:
我正在尝试检测我的字符串中的网站 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'
我该如何解决?
【问题讨论】:
-
你能发布你正在使用的正则表达式吗?具体来说什么是 mutableAttributedString。我的猜测是这条线出了点问题。 [mutableAttributedString replaceCharactersInRange:nameRange withString:[[[mutableAttributedString string] substringWithRange:nameRange] uppercaseString]];您可能希望通过确保每个步骤都符合您的预期来对其进行调试。
-
我相信你是对的。我已经用正则表达式更新了我的代码。还是不知道怎么解决...
标签: iphone cocoa-touch nsstring nsrange