How to extract end code value from given strings

Viewed 50

How to get last code value of string

Emp-Code-001 //Result 001

Sub-000123 //Result 000123

JOB-ABC-BJ-212-0012 //Result  0012

How to pick out end value of code number from given strings.

Here what I did:

func truncateHyphens(id: String){

    let finalString = id
    var trucatedString =id

    let substringToLastIndexOfChar = trucatedString.lastIndexOfCharacter("-") ?? 0
    let otherRange = trucatedString.index(trucatedString.startIndex, offsetBy: substringToLastIndexOfChar + 1)..<trucatedString.endIndex
    trucatedString.removeSubrange(otherRange)
    print(finalString.replacingOccurrences(of: trucatedString, with: ""))

}


public extension String {
    func lastIndexOfCharacter(_ c: Character) -> Int? {
        guard let index = range(of: String(c), options: .backwards)?.lowerBound else
            { return nil }
        return distance(from: startIndex, to: index)
    }
}


self.truncateHyphens(id: "JOB-ABC-BJ-212-12340012") // Result 12340012

It works but I felt not an ideal Solution.

How to optimise the above code?

2 Answers
extension String {
    func separateCharacters(separator: Character) -> [String] {
        return self.split { $0 == separator }.map(String.init)
    }
}

Usage:

print("JOB-ABC-BJ-212-12340012".separateCharacters(separator: "-").last) // Optional("12340012")

Alternative solution with Regular Expression.

The pattern searches for a hyphen plus one or more digits (\\d+) at the end of the string ($). Finally the hyphen will be dropped.

If the pattern cannot be found the function returns nil.

func truncateHyphens(id: String) -> String? {
    let regex = try! NSRegularExpression(pattern: "-\\d+$")
    guard let match = regex.firstMatch(in: id) else { return nil }
    let range = Range(match.range, in: id)!
    return String(id[range].dropFirst())
}
Related