Swift去掉字符串中的HTML标签
Swift去掉字符串中的HTML标签
方法 1:使用 NSAttributedString
提取纯文本
NSAttributedString
可以解析 HTML 并自动去除标签:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import Foundation
extension String {
func removingHTMLTags() -> String {
guard let data = self.data(using: .utf8) else { return self }
if let attributedString = try? NSAttributedString(data: data,
options: [.documentType: NSAttributedString.DocumentType.html,
.characterEncoding: String.Encoding.utf8.rawValue],
documentAttributes: nil) {
return attributedString.string
}
return self
}
}
// 示例
let htmlString = "<p>Hello, <strong>Swift</strong>!</p>"
print(htmlString.removingHTMLTags()) // 输出:Hello, Swift!
✅ 优点:能够解析 HTML 并正确转换 HTML 实体(如 &
→ &
)。 ❌ 缺点:NSAttributedString
可能会丢失部分非标准 HTML 内容。
方法 2:使用正则表达式去除 HTML 标签
1
2
3
4
5
6
7
8
9
10
11
12
import Foundation
extension String {
func strippingHTMLTags() -> String {
let regexPattern = "<[^>]+>"
return self.replacingOccurrences(of: regexPattern, with: "", options: .regularExpression)
}
}
// 示例
let htmlString = "<p>Hello, <strong>Swift</strong>!</p>"
print(htmlString.strippingHTMLTags()) // 输出:Hello, Swift!
✅ 优点:简单高效,适用于去除标签但保留文本。 ❌ 缺点:不会转换 HTML 实体,如 &
仍会存在。
This post is licensed under CC BY 4.0 by the author.