【问题标题】:Trouble with regular expression when using 2 patterns使用 2 种模式时正则表达式出现问题
【发布时间】:2015-04-13 07:02:20
【问题描述】:

我有一个在UITextView 更新期间调用的方法,可以帮助我检测主题标签和用户名提及,例如。 #hashtag@username

如果我一次只尝试检测一个,则此代码可以完美运行。我可以只检测主题标签,或者只检测用户名提及。

我正在尝试让它同时检测到两者。

这是我的两个正则表达式模式:

  1. 标签:#(\\w+)
  2. 用户名:@(\\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


【解决方案1】:

您使用的正则表达式只匹配第一个。如果在开始迭代之前设置断点,您会看到匹配数为 1。

第二件事没有被匹配的原因是因为 | 周围的空格正在被计算。

使用像(#|@)(\\w+) 这样的正则表达式适用于这种情况。我设置了一个示例项目来测试这个正则表达式,它可以工作。

【讨论】:

  • 这种模式在特殊字符 In. 时中断。
  • 如果要捕获特殊字符,可以使用 (\\S+) 而不是 (\\w+)
【解决方案2】:

我刚刚意识到我的带有| (OR) 运算符的代码很好。问题是运算符的每一侧都有一个额外的空间。

这是有效的正则表达式:

[NSRegularExpression regularExpressionWithPattern:@"#(\\w+)|@(\\w+)" options:0 error:&error];

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-11
    • 1970-01-01
    相关资源
    最近更新 更多