skip to Main Content

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


  1. 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?
    
    Login or Signup to reply.
  2. 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)")
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search