2014-01-14 20 views
1

我遇到了一個問題,查找由一對**字符指示的多個子串,並將它們加粗。例如,在此的NSString:如何在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; 

這個代碼只捕獲1雙所以我回來的是:狐狸已經跑到了角落

有什麼想法?

+0

@rmaddy不,不是欺騙。我在那裏問了一個不同的問題。我實際上得到了答案並將其應用於新代碼。這個問題是一個不同的問題 – 3254523

+0

你厭倦了在全球範圍內運行正則表達式替換嗎? – sln

+0

這是怎麼回事?兩者都詢問如何將分隔值轉換爲屬性字符串。 – rmaddy

回答

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"; 
} 
+0

謝謝!效果很好。真棒解決方案 – 3254523

相關問題