-->

如何捕捉多个实例的特殊指示** **字符在一个NSString和大胆它们之间? [重复](how

2019-10-19 04:58发布

这个问题已经在这里有一个答案:

  • 如何捕捉特殊指示** **字符在一个NSString和大胆之间有什么吗? 1个回答

我有一个问题,找到通过一对**字符显示的子串的多个组,并加粗他们。 例如,在此的NSString:

The Fox has **ran** around the **corner**

应改为:狐狸已经指日可待

这里是我的代码:

NSString *questionString = queryString;
NSMutableAttributedString *mutableAttributedString = [[NSMutableAttributedString alloc] initWithString:questionString];

NSRange range = [questionString rangeOfString:@"\\*{2}([^*]+)\\*{2}" options:NSRegularExpressionSearch];
if (range.location != NSNotFound) {
    [mutableAttributedString setAttributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:size]} range:range];
}

[[mutableAttributedString mutableString] replaceOccurrencesOfString:@"**" withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange(0, queryString.length)];

return mutableAttributedString;

这个代码只抓住一对显示的字符,所以我得到的回复是: 狐狸已经指日可待跑

有任何想法吗?

Answer 1:

你必须列举正则表达式的所有比赛。 这是一个有点棘手,因为所有的范围转移时删除限制“**”对。

这似乎做的工作:

NSString *questionString = @"The Fox has **ran** around the **corner**";
NSMutableAttributedString *mutableAttributedString = [[NSMutableAttributedString alloc] initWithString:questionString];

NSError *error = nil;
NSString *pattern = @"(\\*{2})([^*]+)(\\*{2})";
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:pattern options:0 error:&error];

__block NSUInteger shift = 0; // number of characters removed so far
[regex enumerateMatchesInString:questionString options:0 range:NSMakeRange(0, [questionString length])
     usingBlock:^(NSTextCheckingResult *result, NSMatchingFlags flags, BOOL *stop) {
         NSRange r1 = [result rangeAtIndex:1]; // location of first **
         NSRange r2 = [result rangeAtIndex:2]; // location of word in between
         NSRange r3 = [result rangeAtIndex:3]; // location of second **
         // Adjust locations according to the string modifications:
         r1.location -= shift;
         r2.location -= shift;
         r3.location -= shift;
         // Set attribute for the word:
         [mutableAttributedString setAttributes:@{NSFontAttributeName:[UIFont boldSystemFontOfSize:12.0]} range:r2];
         // Remove the **'s:
         [[mutableAttributedString mutableString] deleteCharactersInRange:r3];
         [[mutableAttributedString mutableString] deleteCharactersInRange:r1];
         // Update offset:
         shift += r1.length + r3.length;
     }];

结果(在调试器控制台):

The Fox has {
}ran{
    NSFont = "<UICTFont: 0xc03efb0> font-family: \".HelveticaNeueInterface-MediumP4\"; font-weight: bold; font-style: normal; font-size: 12.00pt";
} around the {
}corner{
    NSFont = "<UICTFont: 0xc03efb0> font-family: \".HelveticaNeueInterface-MediumP4\"; font-weight: bold; font-style: normal; font-size: 12.00pt";
}


文章来源: how to catch multiple instances special indicated **characters** in an NSString and bold them in between? [duplicate]