Swift Regex: Remove numbers embedded inside words in a String - swift

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)

Related

Create an NSPredicate with a line break as part of a string

I need to create a predicate that will look for the following string:
"fred\n5" where \n is a newline.
At least, this is string that is returned when reading the metadata back
You can do it with Regular Expression
let string = """
fred
5
"""
let predicate = NSPredicate(format: "self MATCHES %#", "fred\\n5")
predicate.evaluate(with: string) // true
It's also possible to use the pattern fred(\\n|\\r)5, it considers both linefeed and return.
Alternatively remove the newline character (actually any whitespace and newline characters)
let trimmedString = string.replacingOccurrences(of: "\\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) // 🍏

Remove a line of characters in a String with Swift

I read many questions about removing characters from a string. But none of them resolved my issue.
I have this string:
"\"iconCls\":X.net.RM.getIcon(\"BulletWhite\")"
I want to replace this part:
"X.net.RM.getIcon(\"BulletWhite\")"
By this (double quotes in fact):
"\"\""
I use this code:
let dataString = "\"iconCls\":X.net.RM.getIcon(\"BulletWhite\")"
let newString = dataString?.replacingOccurrences(of: "X.net.RM.getIcon(\"BulletWhite\")" as String, with: "", options: .regularExpression, range: nil)
But it doesn't work. I can replace all characters until I want to replace strings containing parentheses.Any idea? Thanks!
You are passing the .regularExpression option but you are not actually using a regular expression.
Change:
.regularExpression
to:
[]
This gives the result you want:
let dataString = "\"iconCls\":X.net.RM.getIcon(\"BulletWhite\")"
let newString = dataString.replacingOccurrences(of: "X.net.RM.getIcon(\"BulletWhite\")" as String, with: "", options: [], range: nil)
Output:
"icnCls":
Even simpler:
let newString = dataString.replacingOccurrences(of: "X.net.RM.getIcon(\"BulletWhite\")" as String, with: "")
You don't need to use options or range for this.
let str = "\"iconCls\":X.net.RM.getIcon(\"BulletWhite\")"
let replace = "X.net.RM.getIcon(\"BulletWhite\")"
let replaceBy = "\"\""
let newString = str.replacingOccurrences(of: replace, with: replaceBy)

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?
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 (^).