First let me point out... I want to split a String or Substring with any character that is not an alphabet, a number, @ or #. That means, I want to split with whitespaces(spaces & line breaks) and special characters or symbols excluding @ and #
In Android Java, I am able to achieve this with:
String[] textArr = text.split("[^\\w_#@]");
Now, I want to do the same in Swift. I added an extension to String and Substring classes
extension String {}
extension Substring {}
In both extensions, I added a method that returns an array of Substring
func splitWithRegex(by regexStr: String) -> [Substring] {
//let string = self (for String extension) | String(self) (for Substring extension)
let regex = try! NSRegularExpression(pattern: regexStr)
let range = NSRange(string.startIndex..., in: string)
return regex.matches(in: string, options: .anchored, range: range)
.map { match -> Substring in
let range = Range(match.range(at: 1), in: string)!
return string[range]
}
}
And when I tried to use it, (Only tested with a Substring, but I also think String will give me the same result)
let textArray = substring.splitWithRegex(by: "[^\\w_#@]")
print("substring: \(substring)")
print("textArray: \(textArray)")
This is the out put:
substring: This,is a #random @text written for debugging
textArray: []
Please can Someone help me. I don't know if the problem if from my regex [^\\w_#@] or from splitWithRegex method