如何制作突出显示的匹配(NSRegularExpression)?

时间:2014-09-03 12:30:32

标签: ios regex nsregularexpression

我想在TextView中使匹配为蓝色。

NSString *text = @"Except as contained in #wep this notice, the name of a copyright #ololo holder shall not be used in  #pewpewpew advertising or otherwise to #promote";

NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"#\\w*" options:0 error:NULL];
NSArray *matches = [regex matchesInString:text options:0 range:NSMakeRange(0, [text length])];
NSLog(@"count %d", matches.count);

for (NSTextCheckingResult *match in matches) {
    NSRange matchRange = [match range];
    NSString *match = [text substringWithRange:matchRange];
    NSLog(@"Matched string: %@", match);
}
self.myTextView.text = text;

2 个答案:

答案 0 :(得分:1)

您必须创建NSAttributedString然后按照范围应用字体,并将attributedText设置为UITextView而非简单文本。

您的代码应如下所示。

NSMutableAttributedString *attrib = [[NSMutableAttributedString alloc]initWithString:text];

for (NSTextCheckingResult *match in matches) {
    NSRange matchRange = [match range];
    NSString *match = [text substringWithRange:matchRange];
    NSLog(@"Matched string: %@", match);
    // set your rgb color here which you want i added blue color.
    [attrib addAttribute:NSForegroundColorAttributeName
                   value:[UIColor blueColor]
                   range:matchRange];
}
// set attributed text not a normal text.
self.myTextView.attributedText = attrib;

也许这会对你有帮助。

答案 1 :(得分:0)

self.myTextView.attributedText = // your attributed string here