我的问题是如果我想替换整行标签 <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">
最佳答案
尝试:
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?
关于swift - 字符串替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28760111/