我在指定的一對「**」字符之間粗體顯示了任何字符。例如,在此的NSString:如何在NSString中捕獲特殊指示的**字符**並粗體顯示其中的內容?
"The Fox has ran **around** the corner."
應改爲: 「狐狸已經跑周圍角落」
這裏是我的代碼:
NSString *questionString = queryString;
NSMutableAttributedString *mutableAttributedString = [[NSMutableAttributedString alloc] initWithString:questionString];
NSRange range = [questionString rangeOfString:@"\\*([^**]+)\\*" options:NSRegularExpressionSearch|NSCaseInsensitiveSearch];
if (range.location != NSNotFound) {
[mutableAttributedString setAttributes:@{NSFontAttributeName:[UIFont fontWithName:AGHeavyFontName size:size]} range:range];
}
[[mutableAttributedString mutableString] replaceOccurrencesOfString:@"*" withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange(0, queryString.length)];
return mutableAttributedString;
我有issues-這個代碼仍然會捕獲一對「*」的字符,所以在這種情況下,
"The fox has ran *around the corner*
仍然會讀作「狐狸跑左右角」,當它不應該。
任何想法?
這就是爲什麼你不應該使用正則表達式吧。你錯了。特別是,'[^ **]'不會做你認爲它做的事。只需使用'rangeOfString:'(或'componentsSeparatedByString:'和'componentsJoinedByString:')來獲取'**'的兩個實例之間的子串。 – 2014-01-13 23:34:15
@ H2CO3很想看到你在說什麼 – 3254523
@ User3294729579346597634的例子,你可以谷歌,並檢查H2CO3剛剛告訴你什麼。他給了你確切的方法名稱。它不是那麼困難 –