【问题标题】:What's wrong with this Objective-C regex?这个 Objective-C 正则表达式有什么问题?
【发布时间】:2013-11-08 04:06:50
【问题描述】:

我正在尝试检测星号之间的任何单词:

NSString *questionString = @"hello *world*";
NSMutableAttributedString *goodText = [[NSMutableAttributedString alloc] initWithString:questionString]; //should turn the word "world" blue

    NSRange range = [questionString rangeOfString:@"\\b\\*(.+?)\\*\\b" options:NSRegularExpressionSearch|NSCaseInsensitiveSearch];
    if (range.location != NSNotFound) {
        DLog(@"found a word within asterisks - this never happens");
        [goodText addAttribute:NSForegroundColorAttributeName value:[UIColor blueColor] range:range];
    }

但我从来没有得到积极的结果。正则表达式有什么问题?

【问题讨论】:

  • 什么是问题字符串?
  • 那里没有单词边界。尝试添加对零个或多个空白字符的搜索。
  • 查看此链接对您有帮助。 stackoverflow.com/questions/2753956/…
  • 不管空格,但据我所知,仍然没有单词边界。
  • @manujmv 我编辑了问题以显示 questionString。

标签: ios objective-c regex nsattributedstring nsmutableattributedstring


【解决方案1】:
@"\\B\\*([^*]+)\\*\\B"

应该达到你的预期。

根据Difference between \b and \B in regex,您必须使用\B 代替\b 作为字边界。

最后,使用[^*]+ 匹配每对星号,而不是只匹配最外面的。

例如在字符串中

你好*世界*你好吗*你好

它将正确匹配worldare,而不是world how are

实现相同目的的另一种方法是使用?,这将使+ 不贪婪。

@"\\B\\*(.+?)\\*\\B"

另外值得注意的是,rangeOfString:options 返回第一个匹配的范围,而如果您对所有匹配感兴趣,则必须使用该模式构建一个 NSRegularExpression 实例并使用其 matchesInString:options:range: 方法。

【讨论】:

  • 这行得通。但是如果字符串是“hello *world* how *are* you”,“how”也会变成蓝色。
  • 不,它没有。您的代码的其余部分确实如此,因为您使用的是rangeOfString,它将返回第一个匹配项的范围。
  • 如果要检索所有匹配项,则必须使用NSRegularExpression的`matchesInString:options:range:`方法。
  • 谢谢。知道如何在进行正则表达式测试后删除星号吗?我只想把这个词变成蓝色。不应显示星号。我不能在 goodText 上做 stringByReplacingOccurrencesOfString 因为它是一个 NSMutableAttributedString。
  • P.S.在这种情况下,? 并不意味着“可选”,而是意味着“非贪婪”,对吧?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多