字符串替换

时间:2015-02-27 07:58:27

标签: swift

我的问题是如果我想将标记<h1>.....</h1>的整行替换为空字符串""

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=\"https://apppie.files.wordpress.com/2014/09/photo-sep-14-7-40-59-pm_small1.jpg\">"
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)

结果:

<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="https://apppie.files.wordpress.com/2014/09/photo-sep-14-7-40-59-pm_small1.jpg">

1 个答案:

答案 0 :(得分:2)

尝试:

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=\"https://apppie.files.wordpress.com/2014/09/photo-sep-14-7-40-59-pm_small1.jpg\">"

let regex = NSRegularExpression(pattern: "<h1 .*?>.*?</h1>", options: .CaseInsensitive , error: nil)!
let result = regex.stringByReplacingMatchesInString(s, options: nil, range: NSMakeRange(0, (s as NSString).length), withTemplate: "")

// -> <p>Tap the buttons above to see <strong>some cool stuff</strong> with <code>UIWebView</code><p><img src="https://apppie.files.wordpress.com/2014/09/photo-sep-14-7-40-59-pm_small1.jpg">

请注意,这会替换字符串中出现的所有<h1 ...>...</h1>。如果您只想替换第一个:

let regex = NSRegularExpression(pattern: "<h1 .*?>.*?</h1>", options: .CaseInsensitive , error: nil)!
let range = regex.rangeOfFirstMatchInString(s, options: nil, range: NSMakeRange(0, (s as NSString).length))
let result = (s as NSString).stringByReplacingCharactersInRange(range, withString: "")

请注意,这适用于您的字符串,但不适用于每个HTML字符串:请参阅Using regular expressions to parse HTML: why not?