如果您将 html 作为字符串获取,则可以使用正则表达式对其进行解析
// Original string
let htmlString = "<div><br/><div><br/><div style=\"box-sizing: border-box; font-family: 'Segoe UI', 'Helvetica Neue', 'Apple Color Emoji', 'Segoe UI Emoji', Helvetica, Arial, sans-serif; font-size: 14px;\"><br/><div data-tid=\"messageBodyContainer\"><br/><div data-tid=\"messageBodyContent\"><br/><div>Thanks for agreeing to participate in our online bulletin board </div><br/><div><br/></div><br/><div><br/></div><br/></div><br/></div><br/></div><br/></div><br/></div>"
do {
// Let regex tell handle the html matching
let regex = try NSRegularExpression(pattern: "<.*?>", options: NSRegularExpression.Options.caseInsensitive)
// Get the range for the html string
let range = NSMakeRange(0, htmlString.count)
// Replace the regex matches with an empty string
let parsedString = regex.stringByReplacingMatches(in: htmlString, options: NSRegularExpression.MatchingOptions(), range: range, withTemplate: "")
print("PARSED HTML STRING:\n \(parsedString)")
} catch(let error) {
print("Error: \(error.localizedDescription)")
}
由于您无法控制服务器端响应,因此使用 SwiftSoup 库可能会有所帮助。这是一个很好的 html 原生界面。
编辑:
几件事:对不起,我错过了问题的objective-c部分。感谢您使用 Swift 并运行它。其次,如果您不想要带有 html 标签的字符串(我误解了最初的问题),最好的选择是使用stringByReplacingCharactersInRange。这是删除第一个 div 和 br 标记的示例。
NSString *removeFirstPass = @"<div><br/>";
NSRange firstPassRange = [htmlString rangeOfString:removeFirstPass];
if (NSNotFound != firstPassRange.location) {
htmlString = [htmlString stringByReplacingCharactersInRange:firstPassRange withString:@""];
}
NSLog(@"Parsed String: %@", htmlString);
这将为您提供第一个实例并替换它。你会想要找到正确的范围并在你认为合适的时候替换它们。您还需要知道它们在范围内的位置,以便知道您正在替换正确的。