I am trying to get the last sentence from String after ". "(Dot And Space), Suppose I have a very long string and in that string, there are multiple ". "(Dot And Space) but I want to fetch the String after the very last ". "(Dot And Space) I have tried some of the solutions but I am getting below error
Example String: "Hello. playground!. Hello. World!!! How Are you All?"
Expected Output Needed: "World!!! How Are you All?"
Below is the code which I have tried so far
let fullstring = "Hello. playground!. Hello. World!!! How Are you All?"
let outputString = fullstring.substringAfterLastOccurenceOf(". ") // Here I am getting this error Cannot convert value of type 'String' to expected argument type 'Character'
extension String {
var nsRange: NSRange {
return Foundation.NSRange(startIndex ..< endIndex, in: self)
}
subscript(nsRange: NSRange) -> Substring? {
return Range(nsRange, in: self)
.flatMap { self[$0] }
}
func substringAfterLastOccurenceOf(_ char: Character) -> String {
let regex = try! NSRegularExpression(pattern: "(char)\s*(\S[^(char)]*)$")
if let match = regex.firstMatch(in: self, range: self.nsRange), let result = self[match.range(at: 1)] {
return String(result)
}
return ""
}
}
Can anyone help me with this or is there any other way to achieve this?
Thanks in Advance!!
2
Answers
Using
components(separatedBy:)
insteadif you are using
swift 5.7+
andiOS 16.0+
u can use “`regexBuilder”’.