我怎样能够从一个字符串中删除HTML标签,以便输出干净的文本?
let str = string.stringByReplacingOccurrencesOfString("<[^>]+>", withString: "", options: .RegularExpressionSearch, range: nil)
print(str)
我怎样能够从一个字符串中删除HTML标签,以便输出干净的文本?
let str = string.stringByReplacingOccurrencesOfString("<[^>]+>", withString: "", options: .RegularExpressionSearch, range: nil)
print(str)
嗯,我尝试了你的函数,并且它在一个小例子上有效:
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)
<p foo=">现在怎么办?">段落</p>
- The Paramagnetic Croissantstring.replacingOccurrences(of: "<[^>]+>", with: "", options: String.CompareOptions.regularExpression, range: nil)
的意思是使用正则表达式替换字符串中匹配"<[^>]+>"模式的所有内容为空,并返回新的字符串。 - Husam<p>
等的内容。你知道为什么吗? - Konstantinos Natsios由于HTML不是一种正则语言(HTML是一种上下文无关的语言),因此您不能使用正则表达式。请参见:为什么不能使用正则表达式解析HTML?
我建议考虑使用NSAttributedString。
let htmlString = "LCD Soundsystem was the musical project of producer <a href='http://www.last.fm/music/James+Murphy' class='bbcode_artist'>James Murphy</a>, co-founder of <a href='http://www.last.fm/tag/dance-punk' class='bbcode_tag' rel='tag'>dance-punk</a> label <a href='http://www.last.fm/label/DFA' class='bbcode_label'>DFA</a> Records. Formed in 2001 in New York City, New York, United States, the music of LCD Soundsystem can also be described as a mix of <a href='http://www.last.fm/tag/alternative%20dance' class='bbcode_tag' rel='tag'>alternative dance</a> and <a href='http://www.last.fm/tag/post%20punk' class='bbcode_tag' rel='tag'>post punk</a>, along with elements of <a href='http://www.last.fm/tag/disco' class='bbcode_tag' rel='tag'>disco</a> and other styles. <br />"
let htmlStringData = htmlString.dataUsingEncoding(NSUTF8StringEncoding)!
let options: [String: AnyObject] = [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType, NSCharacterEncodingDocumentAttribute: NSUTF8StringEncoding]
let attributedHTMLString = try! NSAttributedString(data: htmlStringData, options: options, documentAttributes: nil)
let string = attributedHTMLString.string
或者,像评论中的Irshad Mohamed一样:
let attributed = try NSAttributedString(data: htmlString.data(using: .unicode)!, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil)
print(attributed.string)
let attributed = try NSAttributedString(data: htmlString.data(using: .unicode)!, options: [NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType], documentAttributes: nil) print(attributed.string)
大多数人更喜欢选择简单易懂的答案。 - Irshad Mohamed在Swift 4中,Mohamed的解决方案是将其作为字符串扩展。
extension String {
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
}
}
}
extension String {
func deleteHTMLTag(tag:String) -> String {
return self.stringByReplacingOccurrencesOfString("(?i)</?\(tag)\\b[^<]*>", withString: "", options: .RegularExpressionSearch, range: nil)
}
func deleteHTMLTags(tags:[String]) -> String {
var mutableString = self
for tag in tags {
mutableString = mutableString.deleteHTMLTag(tag)
}
return mutableString
}
}
这使得从字符串中仅删除<a>
标签成为可能,例如:
let string = "my html <a href="">link text</a>"
let withoutHTMLString = string.deleteHTMLTag("a") // Will be "my html link text"
extension String{
var htmlStripped : String{
return self.replacingOccurrences(of: "<[^>]+>", with: "", options: .regularExpression, range: nil)
}
}
愉快编码
我更喜欢使用正则表达式而不是使用NSAttributedString HTML转换,需要注意的是这种方法非常耗时且需要在主线程上运行。 更多信息请查看此处:https://developer.apple.com/documentation/foundation/nsattributedstring/1524613-initwithdata
对我来说,这个方式很有效,首先我删除任何CSS内联样式,然后再删除所有HTML标签。这种方法可能不如NSAttributedString选项可靠,但对我来说速度要快得多。
extension String {
func withoutHtmlTags() -> String {
let str = self.replacingOccurrences(of: "<style>[^>]+</style>", with: "", options: .regularExpression, range: nil)
return str.replacingOccurrences(of: "<[^>]+>", with: "", options: .regularExpression, range: nil)
}
}
extension String {
public func trimHTMLTags() -> String? {
guard let htmlStringData = self.data(using: String.Encoding.utf8) else {
return nil
}
let options: [NSAttributedString.DocumentReadingOptionKey : Any] = [
.documentType: NSAttributedString.DocumentType.html,
.characterEncoding: String.Encoding.utf8.rawValue
]
let attributedString = try? NSAttributedString(data: htmlStringData, options: options, documentAttributes: nil)
return attributedString?.string
}
}
用途:
let str = "my html <a href='https://www.google.com'>link text</a>"
print(str.trimHTMLTags() ?? "--") //"my html link text"
Swift 4:
extension String {
func deleteHTMLTag(tag:String) -> String {
return self.replacingOccurrences(of: "(?i)</?\(tag)\\b[^<]*>", with: "", options: .regularExpression, range: nil)
}
func deleteHTMLTags(tags:[String]) -> String {
var mutableString = self
for tag in tags {
mutableString = mutableString.deleteHTMLTag(tag: tag)
}
return mutableString
}
}
更新至Swift 4版本:
最初的回答guard let htmlStringData = htmlString.data(using: .unicode) else { fatalError() }
let options: [NSAttributedString.DocumentReadingOptionKey: Any] = [
.documentType: NSAttributedString.DocumentType.html
.characterEncoding: String.Encoding.unicode.rawValue
]
let attributedHTMLString = try! NSAttributedString(data: htmlStringData, options: options, documentAttributes: nil)
let string = attributedHTMLString.string
使用XML
Event-Based Processing和XMLParser,可在所有平台上使用Foundation
,取得了一定的成功。
HTML
不是一种常规语言。HTML
虽然与XML
非常相似,但它们并不相同。在尝试将其解析为XML
之前,您可能需要清理您的HTML
。<br>
和<hr>
会导致解析失败,但<br />
和<hr />
将被解析为\n
。NSObject
协议和基于事件的处理。XMLParser
已经很长时间没有更新了,因此缺乏我们想要的许多新的Swift功能。Foundation
,但它仅在macOS上可用。针对我的使用情况,我创建了一个类,使我能够使用async/await
和异步处理。
请随意调整以适应您自己的用例,也许可以改进原始HTML
字符串的清理过程。
import Foundation
final class Parser: NSObject, XMLParserDelegate {
private(set) var result = ""
private var finished: (() -> Void)?
private var fail: ((Error) -> Void)?
private var content = ""
init(html: String) async throws {
super.init()
result = try await withUnsafeThrowingContinuation { [weak self] continuation in
// tweak here as needed
let clean = html
.replacingOccurrences(of: "<!DOCTYPE html>",
with: "",
options: .caseInsensitive)
.replacingOccurrences(of: "<br>",
with: "\n",
options: .caseInsensitive)
.replacingOccurrences(of: "<hr>",
with: "\n",
options: .caseInsensitive)
let xml = XMLParser(data: .init(("<xml>" + clean + "</xml>").utf8))
self?.finished = { [weak self] in
xml.delegate = nil
self?.fail = nil
self?.finished = nil
guard let content = self?.content else { return }
continuation
.resume(returning: content
.trimmingCharacters(in:
.whitespacesAndNewlines))
}
self?.fail = { [weak self] in
xml.delegate = nil
self?.fail = nil
self?.finished = nil
xml.abortParsing()
continuation
.resume(throwing: $0)
}
xml.delegate = self
if !xml.parse(),
let error = xml.parserError {
self?.fail?(error)
}
}
}
func parserDidEndDocument(_: XMLParser) {
finished?()
}
func parser(_: XMLParser, parseErrorOccurred: Error) {
fail?(parseErrorOccurred)
}
func parser(_: XMLParser, validationErrorOccurred: Error) {
fail?(validationErrorOccurred)
}
func parser(_: XMLParser, foundCharacters: String) {
content += foundCharacters
}
}
利用此帖子中已经给出的一些示例
let string = "<!DOCTYPE html> <html> <body> <h1>My First Heading</h1> <p>My first paragraph.</p> </body> </html>"
let result = try await Parser(html: string).result
// My First Heading My first paragraph.
let string = "LCD Soundsystem was the musical project of producer <a href='http://www.last.fm/music/James+Murphy' class='bbcode_artist'>James Murphy</a>, co-founder of <a href='http://www.last.fm/tag/dance-punk' class='bbcode_tag' rel='tag'>dance-punk</a> label <a href='http://www.last.fm/label/DFA' class='bbcode_label'>DFA</a> Records. Formed in 2001 in New York City, New York, United States, the music of LCD Soundsystem can also be described as a mix of <a href='http://www.last.fm/tag/alternative%20dance' class='bbcode_tag' rel='tag'>alternative dance</a> and <a href='http://www.last.fm/tag/post%20punk' class='bbcode_tag' rel='tag'>post punk</a>, along with elements of <a href='http://www.last.fm/tag/disco' class='bbcode_tag' rel='tag'>disco</a> and other styles. <br />"
let result = try await Parser(html: string).result
// LCD Soundsystem was the musical project of producer James Murphy, co-founder of dance-punk label DFA Records. Formed in 2001 in New York City, New York, United States, the music of LCD Soundsystem can also be described as a mix of alternative dance and post punk, along with elements of disco and other styles.
let string = "my html <a href=\"\">link text</a>"
let result = try await Parser(html: string).result
// my html link text