我正在尝试检测星号之间的任何单词:
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];
}
但我从来没有得到积极的结果。正则表达式有什么问题?
最佳答案
@"\\B\\*([^*]+)\\*\\B"
应该达到您的期望。
根据 Difference between \b and \B in regex,您必须使用 \B
代替 \b
作为字边界.
最后,使用 [^*]+
匹配每对星号,而不是仅匹配最外层的星号。
例如,在字符串中
Hello *world* how *are* you
它将正确匹配 world
和 are
,而不是 world how are
。
实现相同目的的另一种方法是使用 ?
这将使 +
成为非贪婪的。
@"\\B\\*(.+?)\\*\\B"
还值得注意的是 rangeOfString:options
返回第一个匹配的范围,而如果您对所有匹配感兴趣,您必须使用构建一个 NSRegularExpression
实例使用该模式并使用其 matchesInString:options:range:
方法。
关于ios - 这个 Objective-C 正则表达式有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19851408/