Ios 按模式生成动态文本属性

Ios 按模式生成动态文本属性,ios,swift,uilabel,nsattributedstring,nsattributedstringkey,Ios,Swift,Uilabel,Nsattributedstring,Nsattributedstringkey,我有一根这样的绳子 var str = "This is &my& apple, I bought it %yesterday%" &&mark内的所有内容均为斜体,mark内的%%将变为粗体,并将此数据设置为UILabel。最终结果将是: 这是我的苹果,我昨天买的 已编辑:我使用%.*?%作为正则表达式模式来提取子字符串 有没有办法解决这个问题?请帮忙 提前感谢。您可以使用regex的replacingOccurrences在粗体和斜体html标记之间放置匹配项,然后使用NS

我有一根这样的绳子

var str = "This is &my& apple, I bought it %yesterday%"
&&mark内的所有内容均为斜体,mark内的%%将变为粗体,并将此数据设置为UILabel。最终结果将是:

这是我的苹果,我昨天买的

已编辑:我使用%.*?%作为正则表达式模式来提取子字符串

有没有办法解决这个问题?请帮忙


提前感谢。

您可以使用regex的replacingOccurrences在粗体和斜体html标记之间放置匹配项,然后使用NSAttributedString将html字符串转换为属性字符串

let str = "This is &my& apple, I bought it %yesterday%"

let html = str
    .replacingOccurrences(of: "(&.*?&)", with: "<b>"+"$1"+"</b>", options: .regularExpression)
    .replacingOccurrences(of: "&(.*?)&", with: "$1", options: .regularExpression)
    .replacingOccurrences(of: "(%.*?%)", with: "<i>"+"$1"+"</i>", options: .regularExpression)
    .replacingOccurrences(of: "%(.*?)%", with: "$1", options: .regularExpression)

谢谢你的帮助。它正在工作,但向我显示了一个关于事务中调用的+[CatTransaction synchronize]的警告,您知道它是什么,以及如何静音吗it@user3783161我认为这与上面的代码无关。尝试隔离你的问题,如果你发布了一个示例项目,我可以看一看。谢谢你的帮助,我找到了问题并解决了
let label = UILabel(frame: CGRect(origin: .zero, size: CGSize(width: 300, height: 50)))
label.font = UIFont.systemFont(ofSize: 14)
do {
    label.attributedText = try NSAttributedString(data: Data(html.utf8), options: [.documentType: NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue], documentAttributes: nil)
} catch {
    print("error:", error)
}