【问题标题】:How to catch special indicated **characters** in an NSString and bold what's in between?如何在 NSString 和粗体之间捕获特殊指示的**字符**?
【发布时间】: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


【解决方案1】:

也许这对你有帮助:

http://regex101.com/r/eF6pJ8

\\*{2}([^*]*)\\*{2}

【讨论】:

  • 不幸的是,这对我不起作用,我收到“未知转义序列”警告
  • 您可能需要转义反斜杠:\\*{2}([^*]*)\\*{2}
猜你喜欢
  • 1970-01-01
  • 2017-11-10
  • 1970-01-01
  • 2015-06-12
  • 2011-11-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多