나의 발자취

API 결과값 안에 tag가 있을 때 - Regex 본문

앱 개발/iOS

API 결과값 안에 tag가 있을 때 - Regex

달모드 2024. 9. 10. 11:10

간혹가다 API 결과값에 태그가 있는 경우가 있다. 그럴 때는 Regex로 없애주면 되는데, 문제점은 제목 구분자로 <제목> 이런 식으로 쓴 것들은 다 날아간다.

 

extension String {
    var stripHTML: String {
        return self.replacingOccurrences(of: "<[^>]+>", with: "", options: .regularExpression)
    }
    
    func stripOutHtml() -> String? {
        do {
            guard let data = self.data(using: .unicode) else {
                return nil
            }
            let attributed = try NSAttributedString(data: data, options: [.documentType:NSAttributedString.DocumentType.html, .characterEncoding: String.Encoding.utf8.rawValue], documentAttributes: nil)
            return attributed.string
        } catch {
            return nil
        }
    }
}
728x90
반응형
Comments