通过模式生成动态文本属性

Generate dynamic text attribute by pattern

我有这样的字符串

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

& & 标记内的所有内容将变为斜体,% % 标记内的所有内容将变为粗体并将此数据设置为 UILabel。最终输出将是:

This is my apple, I bought it yesterday

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

有什么办法可以解决这个问题吗?请帮助

提前致谢。

您可以使用正则表达式的 replacingOccurrences 来匹配粗体和斜体 html 标签,然后使用 NSAttributedString 将您的 html 字符串转换为属性字符串。

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

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

正在将您的 html 转换为属性字符串

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)
}