Remove a line of characters in a String with Swift - 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)

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)

Replace in string with regex

I am struggling to modify captured value with regex.
For example, I wanna change "Hello, he is hero" to "HEllo, HE is HEro" using Regex.
I know there are ways to change this without regex, but it is just an example to show the problem. I actually use the regex instead of just he, but I cannot provide it here. That is why using regex is required.
The code below somehow does not work. Are there any ways to make it work?
"Hello, he is hero".replacingOccurrences(
of: #"(he)"#,
with: "$1".uppercased(), // <- uppercased is not applied
options: .regularExpression
)
You need to use your regex in combination with Range (range(of:)) to find matches and then replace each found range separately
Here is a function as an extension to String that does this by using range(of:) starting from the start of the string and then moving the start index to match from forward to after the last match. The actual replacement is done inside a separate function that is passed as an argument
extension String {
func replace(regex: String, with replace: (Substring) -> String) -> String {
var string = self
var startIndex = self.startIndex
let endIndex = self.endIndex
while let range = string.range(of: regex, options: [.regularExpression] , range: startIndex..<endIndex) {
if range.isEmpty {
startIndex = string.index(startIndex, offsetBy: 1)
if startIndex >= endIndex { break }
continue
}
string.replaceSubrange(range, with: replace(string[range]))
startIndex = range.upperBound
}
return string
}
}
Example where we do an case insensitive search for words starting with "he" and replace each match with the uppercased version
let result = "Hello, he is hero. There he is".replace(regex: #"(?i)\bhe"#) {
$0.uppercased()
}
Output
HEllo, HE is HEro. There HE is
You can try NSRegularExpression. Something like:
import Foundation
var sourceStr = "Hello, he is hero"
let regex = try! NSRegularExpression(pattern: "(he)")
let matches = regex.matches(in: sourceStr, range: NSRange(sourceStr.startIndex..., in: sourceStr))
regex.enumerateMatches(in: sourceStr, range: NSRange(sourceStr.startIndex..., in: sourceStr)) { (match, _, _) in
guard let match = match else { return }
guard let range = Range(match.range, in: sourceStr) else { return }
let sub = sourceStr[range]
sourceStr = sourceStr.replacingOccurrences(of: sub, with: sub.uppercased(), options: [], range: range)
}
print(sourceStr)
this is the solution i can provide
var string = "Hello, he is hero"
let occurrence = "he"
string = string.lowercased().replacingOccurrences(
of: occurrence,
with: occurrence.uppercased(),
options: .regularExpression
)
print(string)

Swift - Getting only AlphaNumeric Characters from String

I'm trying to create an internal function for the String class to get only AlphaNumeric characters and return a string. I'm running into a few errors with how to convert the matches back into a string using Regex. Can someone tell me how to fix the code or if there's an easier way?
I want something like this
let testString = "_<$abc$>_"
let alphaNumericString = testString.alphaNumeric() //abc
So far I have:
extension String {
internal func alphaNumeric() -> String {
let regex = try? NSRegularExpression(pattern: "[^a-z0-9]", options: .caseInsensitive)
let string = self as NSString
let results = regex?.matches(in: self, options: [], range: NSRange(location: 0, length: string.length))
let matches = results.map {
String(self[Range($0.range, in: self)!])
}
return matches.join()
}
}
You may directly use replacingOccurrences (that removes all non-overlapping matches from the input string) with [^A-Za-z0-9]+ pattern:
let str = "_<$abc$>_"
let pattern = "[^A-Za-z0-9]+"
let result = str.replacingOccurrences(of: pattern, with: "", options: [.regularExpression])
print(result) // => abc
The [^A-Za-z0-9]+ pattern is a negated character class that matches any char but the ones defined in the class, one or more occurrences (due to + quantifier).
See the regex demo.
Try below extension:
extension String {
var alphanumeric: String {
return self.components(separatedBy: CharacterSet.alphanumerics.inverted).joined().lowercased()
}
}
Usage: print("alphanumeric :", "_<$abc$>_".alphanumeric)
Output : abc
You can also use characterset for this like
extension String {
var alphaNumeric: String {
components(separatedBy: CharacterSet.alphanumerics.inverted).joined()
}
}

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) // 🍏

How can I substring this string?

how can I substring the next 2 characters of a string after a certian character. For example I have a strings str1 = "12:34" and other like str2 = "12:345. I want to get the next 2 characters after : the colons.
I want a same code that will work for str1 and str2.
Swift's substring is complicated:
let str = "12:345"
if let range = str.range(of: ":") {
let startIndex = str.index(range.lowerBound, offsetBy: 1)
let endIndex = str.index(startIndex, offsetBy: 2)
print(str[startIndex..<endIndex])
}
It is very easy to use str.index() method as shown in #MikeHenderson's answer, but an alternative to that, without using that method is iterating through the string's characters and creating a new string for holding the first two characters after the ":", like so:
var string1="12:458676"
var nr=0
var newString=""
for c in string1.characters{
if nr>0{
newString+=String(c)
nr-=1
}
if c==":" {nr=2}
}
print(newString) // prints 45
Hope this helps!
A possible solution is Regular Expression,
The pattern checks for a colon followed by two digits and captures the two digits:
let string = "12:34"
let pattern = ":(\\d{2})"
let regex = try! NSRegularExpression(pattern: pattern, options: [])
if let match = regex.firstMatch(in: string, range: NSRange(location: 0, length: string.characters.count)) {
print((string as NSString).substring(with: match.rangeAt(1)))
}