0

I have a string like this

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

Everything inside & & mark will be italics, inside % % mark will turn into bold style and set this data to a UILabel. The final output will be:

This is my apple, I bought it yesterday

Edited: I am using %(.*?)% as a regex pattern to extract the substring

Is there any way to solve this issue? Please help

Thanks in advance.

Shin622
  • 645
  • 3
  • 7
  • 22

1 Answers1

1

You can use replacingOccurrences of regex to put the matches between bold and italic html tags and then use NSAttributedString to convert your html string to attributed string.

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)

Converting your html to attributed string

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)
}
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
  • thanks for your help. It's working but showing me a warning about "+[CATransaction synchronize] called within transaction", do you know what is it and how to silent it – Shin622 Nov 12 '17 at 15:28
  • @user3783161 I don't think thats related to the code above. Try isolating your issue and if you post a sample project I can take a look at it. – Leo Dabus Nov 12 '17 at 15:30
  • 1
    thanks for helping me, I figure out the problem and solved – Shin622 Nov 13 '17 at 04:22