2017-02-27 8 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. 
関連する問題