Swift replace full line in String - swift

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?
Edit:
It is not working anymore when its between a string:
let str = "Test \n Mieter: \n Hausverwalter: \n Firma: \n"
str.stringByReplacingOccurrencesOfString("^Mieter[^\n]+\\s", withString: "", options: .RegularExpressionSearch, range: nil)
// so "Mieter \n" is not being replaced.

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
Edit:
If the substring is not at the beginning of the string remove the leading caret (^).

Related

Swift Regex: Remove numbers embedded inside words in a String

Goal: Remove numbers embedded inside a string.
Example: let testString = "5What's9 wi3th this pro9ject I'm try905ing to build."
Desired Output: testString = "5What's9 with this project I'm trying to build"
What I've Tried:
let resultString = testString
.replacingOccurrences(of: "\\b[:digit:]\\b", with: "", options: .regularExpression)
// fails, returns string as is
let resultString = testString
.replacingOccurrences(of: "(\\d+)", with: "", options: .regularExpression)
// fails, returns all numbers removed from string.. close
let resultString = testString
.replacingOccurrences(of: "[0-9]", with: "", options: .regularExpression)
// removes all numbers from string.. close
How can we remove numbers that are inside of words only?
We can try doing a regex replacement on the following pattern:
(?<=\S)\d+(?=\S)
This matches only numbers surrounded on both sides by non whitespace characters. Updated code:
let resultString = testString
.replacingOccurrences(of: "(?<=\\S)\\d+(?=\\S)", with: "", options: .regularExpression)

Regex replace spaces at each new lines

I am saving users input to db as a string and I would like to remove all spaces at each lines.
Input from user:
Hi!
My name is:
Bob
I am from the USA.
I want to remove spaces between "Bob", so the result will be:
Hi!
My name is:
Bob
I am from the USA.
I am trying to do it with the following code
let regex = try! NSRegularExpression(pattern: "\n[\\s]+", options: .caseInsensitive)
a = regex.stringByReplacingMatches(in: a, options: [], range: NSRange(0..<a.utf16.count), withTemplate: "\n")
but this code replace multiple new lines "\n", I don't want to do it.
After I run the above code: "1\n\n\n 2" -> "1\n2". The result I need: "1\n\n\n2" (only spaces are removed, not new lines).
No need for regex, split the string on the new line character into an array and then trim all lines and join them together again
let trimmed = string.components(separatedBy: .newlines)
.map { $0.trimmingCharacters(in: .whitespaces) }
.joined(separator: "\n")
or you can use reduce
let trimmed = string.components(separatedBy: .newlines)
.reduce(into: "") { $0 += "\($1.trimmingCharacters(in: .whitespaces))\n"}
You can use
let regex = try! NSRegularExpression(pattern: "(?m)^\\h+", options: .caseInsensitive)
Actually, as there are no case chars in the pattern, you may remove .caseInsensitive and use:
let regex = try! NSRegularExpression(pattern: "(?m)^\\h+", options: [])
See the regex demo. The pattern means:
(?m) - turn on multiline mode
^ - due to (?m), it matches any line start position
\h+ - one or more horizontal whitespaces.
Swift code example:
let txt = "Hi!\n\nMy name is:\n Bob\n\nI am from the USA."
let regex = "(?m)^\\h+"
print( txt.replacingOccurrences(of: regex, with: "", options: [.regularExpression]) )
Output:
Hi!
My name is:
Bob
I am from the USA.

Remove occurrence of Unicode character \u{ef} from String In Swift 3

Remove occurrence of Unicode character \u{ef} from String In Swift 3.
Example String:- "\u{ef}\n \n\u{ef}\n 🍏\n\u{ef}"
Thanks In advance.
Use the replacingOccurrences on your String:
let str = "\u{ef}\n \n\u{ef}\n 🍏\n\u{ef}".trimmingCharacters(in: .whitespaces)
let newStr = str.replacingOccurrences(of: "\u{ef}", with: "", options: NSString.CompareOptions.literal, range:nil)
print(newStr) // 🍏

Replace all characters in a String in Swift

Just trying to do a play around with Swift String. I want to replace all the characters in a String to a blank space.
inputString = "This is a String"
outputString = " "
How could I achieve this in swift?
You can use the map function to replace any character with another:
String("foo".characters.map { _ in Character(" ") })
One possible way:
outputString = String(count: inputString.characters.count, repeatedValue: (" " as Character))
Another way:
let outputString = inputString.replacingOccurrences(of: "[^\\s]",
with: " ",
options: .regularExpression,
range: inputString.startIndex..<inputString.endIndex)
So given an input String of n chars you want another String of n blank spaces, right?
let inputString = "This is a String"
let outputString = String([Character](count: inputString.characters.count, repeatedValue: " "))

Remove last punctuation of a swift string

I'm trying to remove the last punctuation of a string in swift 2.0
var str: String = "This is a string, but i need to remove this comma, \n"
var trimmedstr: String = str.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet())
First I'm removing the the white spaces and newline characters at the end, and then I need to check of the last character of trimmedstr if it is a punctuation. It can be a period, comma, dash, etc, and if it is i need to remove it it.
How can i accomplish this?
There are multiple ways to do it. You can use contains to check if the last character is in the set of expected characters, and use dropLast() on the String to construct a new string without the last character:
let str = "This is a string, but i need to remove this comma, \n"
let trimmedstr = str.trimmingCharacters(in: .whitespacesAndNewlines)
if let lastchar = trimmedstr.last {
if [",", ".", "-", "?"].contains(lastchar) {
let newstr = String(trimmedstr.dropLast())
print(newstr)
}
}
Could use .trimmingCharacters(in:.whitespacesAndNewlines) and .trimmingCharacters(in: .punctuationCharacters)
for example, to remove whitespaces and punctuations on both ends of the String-
let str = "\n This is a string, but i need to remove this comma and whitespaces, \t\n"
let trimmedStr = str.trimmingCharacters(in:
.whitespacesAndNewlines).trimmingCharacters(in: .punctuationCharacters)
Result -
This is a string, but i need to remove this comma and whitespaces