对于数据库程序中的输出,我插入了一些标记以指示粗体或斜体的文本,以及一些替换图像的文本。例如:
“%Important% ^所有员工到休息室^”的最终输出应为:
重要 的所有员工到休息室
我编写了代码来查找带有“%”符号和“^”符号的文本,但我现在遇到的问题是文本输出如下:
%重要% ^所有员工到休息室^
我想删除这些 % 和 ^,同时保留字符串的格式。
这是我一直在使用的代码,直到它中断:
func processText(inString string: String) -> NSAttributedString {
let pattern = ["(?<=\\^).*?(?=\\^)","(?<=\\%).*?(?=\\%)","\\^", "\\%"]
let italicsRegex = NSRegularExpression(pattern: pattern[0], options: .allZeros, error: nil)
let range = NSMakeRange(0, count(string))
let italicsMatches = italicsRegex?.matchesInString(string, options: .allZeros, range: range) as? [NSTextCheckingResult]
var attributedText = NSMutableAttributedString(string: string)
for match in italicsMatches! {
attributedText.addAttribute(NSFontAttributeName, value: UIFont(name: "Helvetica-Oblique", size: 14.0)!, range: match.range)
}
let boldRegex = NSRegularExpression(pattern: pattern[1], options: .allZeros, error: nil)
let boldMatches = boldRegex?.matchesInString(string, options: .allZeros, range: range) as? [NSTextCheckingResult]
for match in boldMatches! {
attributedText.addAttribute(NSFontAttributeName, value: UIFont(name: "Helvetica-Bold", size: 14.0)!, range: match.range)
}
let removeItalicsMarksRegex = NSRegularExpression(pattern: pattern[2], options: .allZeros, error: nil)
let removeItalicsMarksMatches = removeItalicsMarksRegex?.matchesInString(string, options: .allZeros, range: range) as? [NSTextCheckingResult]
var numberOfLoops = 0
for match in removeItalicsMarksMatches! {
attributedText.replaceCharactersInRange(match.range, withString: "")
}
return attributedText.copy() as! NSAttributedString
}
这适用于 % 匹配(但仅适用于第一个字符)并立即导致 ^ 字符崩溃。
任何有关解决此问题的帮助或建议将不胜感激。谢谢。