2017-02-27 78 views
-7

我有很多字符串,像這樣:快速替換字符之間的字符串

'這是一個「表」。 「桌子上」有一個「蘋果」。

我想用空格替換「table」,「apple」和「table」。有沒有辦法做到這一點?

回答

3

一個簡單的正則表達式:

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 ____ 

如果你想保持相同的字符數,那麼你可以在比賽迭代:

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.