一尘不染

从字符串中剥离HTML标记

swift

如何从字符串中删除HTML标签,以便可以输出纯文本?

let str = string.stringByReplacingOccurrencesOfString("<[^>]+>", withString: "", options: .RegularExpressionSearch, range: nil)
print(str)

阅读 265

收藏
2020-07-07

共1个答案

一尘不染

嗯,我尝试了您的功能,并在一个小例子上工作了:

var string = "<!DOCTYPE html> <html> <body> <h1>My First Heading</h1> <p>My first paragraph.</p> </body> </html>"
let str = string.stringByReplacingOccurrencesOfString("<[^>]+>", withString: "", options: .RegularExpressionSearch, range: nil)
print(str)

//output "  My First Heading My first paragraph. "

你能举一个例子吗?

Swift 4和5版本:

var string = "<!DOCTYPE html> <html> <body> <h1>My First Heading</h1> <p>My first paragraph.</p> </body> </html>"
let str = string.replacingOccurrences(of: "<[^>]+>", with: "", options: .regularExpression, range: nil)
2020-07-07