swift - 字符串替换

标签 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">

最佳答案

尝试:

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/

相关文章:

ios - 如何使用 Kingfisher 在 UIButton 的 setBackgroundImage 期间设置 indicatorType

ios - SwiftUI:onAppear 的奇怪行为

ios - NEPacketTunnelProvider 嗅探器 iOS

ios - 将数据从 TableView Controller 传递到选项卡 View 中包含的另一个 View Controller ?

Swift:正则表达式函数返回空数组

swift - xcode 中的外部库使用

swift - 照片编辑扩展问题 (iOS 8)

iOS googlemobilevision 文本识别库快速集成

ios swift,在 NSArray 中传递 Parse PFbject

swift - 尝试在 SwiftUI 中使用时,实例方法 'appendInterpolation' 要求 'Decimal' 符合 '_FormatSpecifiable'