【发布时间】:2015-04-13 07:02:20
【问题描述】:
我有一个在UITextView 更新期间调用的方法,可以帮助我检测主题标签和用户名提及,例如。 #hashtag 和 @username
如果我一次只尝试检测一个,则此代码可以完美运行。我可以只检测主题标签,或者只检测用户名提及。
我正在尝试让它同时检测到两者。
这是我的两个正则表达式模式:
- 标签:
#(\\w+) - 用户名:
@(\\w+)
这是我的检测方法:
- (NSMutableAttributedString*)decorateTags:(NSString *)stringWithTags{
NSError *error = nil;
// Hashtag detection
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"#(\\w+) | @(\\w+)" options:0 error:&error];
NSArray *matches = [regex matchesInString:stringWithTags options:0 range:NSMakeRange(0, stringWithTags.length)];
NSMutableAttributedString *attString=[[NSMutableAttributedString alloc] initWithString:stringWithTags];
NSInteger stringLength = [stringWithTags length];
for (NSTextCheckingResult *match in matches) {
NSRange wordRange = [match rangeAtIndex:0];
NSString* word = [stringWithTags substringWithRange:wordRange];
// Set Foreground Color
UIColor *foregroundColor = [UIColor blueColor];
[attString addAttribute:NSForegroundColorAttributeName value:foregroundColor range:wordRange];
NSLog(@"Found tag %@", word);
}
return attString;
}
上面的代码运行良好,但就像我说的那样,它目前只设置为一次检测一个。所以我修改了正则表达式模式来搜索主题标签和用户名提及,我尝试使用几个运算符,如|, +, *, *+, ++, +, 等,但它们都不允许同时检测主题标签和用户名,为了清楚这就是我的意思:
“嘿@John看看这个#hashtag”
看看两者是如何突出显示的?这就是我需要的,但是在使用苹果正则表达式文档中提供的运算符进行测试后,我只能得到一个突出显示或根本没有。
例如上面的示例代码,#hashtag 会突出显示,但@John 不会。
以下是我尝试使用运算符的一些简单示例:
[NSRegularExpression regularExpressionWithPattern:@"#(\\w+) + @(\\w+)" options:0 error:&error];
[NSRegularExpression regularExpressionWithPattern:@"#(\\w+) | @(\\w+)" options:0 error:&error];
[NSRegularExpression regularExpressionWithPattern:@"#(\\w+) * @(\\w+)" options:0 error:&error];
【问题讨论】:
-
"(]*?>)|
标签: ios objective-c regex nsregularexpression