【发布时间】:2014-02-01 21:59:37
【问题描述】:
我无法将指定的一对“**”字符之间的任何字符加粗。例如,在这个 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;
我遇到了问题——这段代码仍然会捕获带有一对“*”的字符,所以在这种情况下,
"The fox has ran *around the corner*
在不应该的时候仍会读作“狐狸已经绕过拐角处”。
有什么想法吗?
【问题讨论】:
-
这就是为什么你不应该使用正则表达式。你搞错了。特别是,
[^**]并没有按照您的想法去做。只需使用rangeOfString:(或componentsSeparatedByString:和componentsJoinedByString:)来获取**的两个实例之间的子字符串。 -
@H2CO3 很想看看你所说的例子
-
@User3294729579346597634 你可以用谷歌搜索一下 H2CO3 刚刚告诉你的内容。他给了你确切的方法名称。没那么难
标签: ios objective-c regex nsregularexpression