vendredi 27 février 2015

Swift: String replacements

My question is how if i want to replace whole line of the tag <h1></h1> in to a empty string "" .



var s = "<h1 style=\"font-family: Helvetica\">Hello Pizza</h1><p>Tap the buttons above to see <strong>some cool stuff</strong> with <code>UIWebView</code><p><img src=\"http://ift.tt/1AQlAJw\">"
var search = "<\\/?strong>"
var replaceWith = ""
var replacementLength = count(replaceWith)
var err: NSError? = nil

var expr = NSRegularExpression(pattern: search, options: .CaseInsensitive, error: &err)

if let matches = expr?.matchesInString(s, options: nil, range: NSMakeRange(0, count(s)) ) {
var replacedStringLengthDifference = 0
for match in matches {
var startIndex = advance(s.startIndex, (match.range.location + replacedStringLengthDifference))
var endIndex = advance(s.startIndex, (match.range.length + match.range.location + replacedStringLengthDifference))
replacedStringLengthDifference -= (match.range.length - replacementLength)
s.replaceRange(startIndex..<endIndex, with: replaceWith)
}
}

println(s)


Result:


<h1 style="font-family: Helvetica">Hello Pizza</h1><p>Tap the buttons above to see some cool stuff with <code>UIWebView</code><p><img src="http://ift.tt/1AQlAJw">




Aucun commentaire:

Enregistrer un commentaire