0

我有一个这样的字符串

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

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

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

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

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

提前致谢。

4

1 回答 1

1

您可以使用正则表达式的 replaceOccurrences 在粗体和斜体 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)

将您的 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)
}
于 2017-11-12T14:48:05.880 回答