derdida derdida - 6 months ago 37
Swift Question

Swift replace full line in String

I have multiple lines in an String, for example:

let str = "Mieter: Hannes Tester \nVerwalter: Michael Karner \n"

Now i want to remove the whole sentence between "Mieter" and the line break. So the result should be:

let str = "Verwalter: Michael Karner \n"

I could check with Regex, but i am only able to get the string between 2 words. For example with:

if let match = str.rangeOfString("(?<=Mieter)[^\n]+", options: .RegularExpressionSearch) {
print(str.substringWithRange(match)) // between

But how can i replace a whole line?


Use replacingOccurrencesOf

let str = "Mieter: Hannes Tester \nVerwalter: Michael Karner \n"
str.replacingOccurrences(of: "^Mieter[^\n]+\\s", with: "", options: .regularExpression)

This is Swift 3 code