快速替换字符之间的字符串

Ann*_*nie -7 swift

我有很多字符串,像这样:

'这是一张桌子”。“桌子”上有一个“苹果”。

我想用空格替换“table”、“apple”和“table”。有没有办法做到这一点?

Sul*_*han 5

一个简单的正则表达式:

let sentence = "This is \"table\". There is an \"apple\" on the \"table\""

let pattern = "\"[^\"]+\"" //everything between " and "
let replacement = "____"
let newSentence = sentence.replacingOccurrences(
    of: pattern,
    with: replacement,
    options: .regularExpression
)

print(newSentence) // This is ____. There is an ____ on the ____
Run Code Online (Sandbox Code Playgroud)

如果要保持相同数量的字符,则可以遍历匹配项:

let sentence = "This is table. There is \"an\" apple on \"the\" table."    
let regularExpression = try! NSRegularExpression(pattern: "\"[^\"]+\"", options: [])

let matches = regularExpression.matches(
    in: sentence,
    options: [],
    range: NSMakeRange(0, sentence.characters.count)
)

var newSentence = sentence

for match in matches {
    let replacement = Array(repeating: "_", count: match.range.length - 2).joined()
    newSentence = (newSentence as NSString).replacingCharacters(in: match.range, with: "\"" + replacement + "\"")
}

print(newSentence) // This is table. There is "__" apple on "___" table.
Run Code Online (Sandbox Code Playgroud)