0

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!!

1

2 Answers 2

2

Using components(separatedBy:) instead

let fullstring = "Hello. playground!. Hello. World!!! How Are you All?" let sliptArr = fullstring.components(separatedBy: ". ") print(sliptArr[sliptArr.count - 1]) // World!!! How Are you All? 
Sign up to request clarification or add additional context in comments.

2 Comments

For your second example, spit separator takes self.Element which is a Character and not a string.
Dear @JohnHanley, I was mistaken. Thank you sir
0

if you are using swift 5.7+ and iOS 16.0+ u can use ```regexBuilder'''.

let text = "Hello. playground!. Hello. World!!! How Are you All?" let regex = Regex { Optionally{ ZeroOrMore(.any) ". " } Capture { ZeroOrMore(.any) } } if let lastSentence = try? regex.wholeMatch(in: text) { print("lastSentence: \(lastSentence.output.1)") } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.