Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.8k views
in Technique[技术] by (71.8m points)

Replace string between characters in swift

I have many strings, like this:

'This is a "table". There is an "apple" on the "table".'

I want to replace "table", "apple" and "table" with spaces. Is there a way to do it?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

A simple regular expression:

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 ____

If you want to keep the same number of characters, then you can iterate over the matches:

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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...