Skip to content

Instantly share code, notes, and snippets.

@moutend
Created January 9, 2022 04:03
Show Gist options
  • Save moutend/45999e1ad5fd404ebd43bb4b72d9b9d8 to your computer and use it in GitHub Desktop.
Save moutend/45999e1ad5fd404ebd43bb4b72d9b9d8 to your computer and use it in GitHub Desktop.
Get suffix number from file name
import Foundation
extension String {
func trimPrefix(_ prefix: String) -> String {
guard self.hasPrefix(prefix) else {
return self
}
return String(self.dropFirst(prefix.count))
}
func trimSuffix(_ suffix: String) -> String {
guard self.hasSuffix(suffix) else {
return self
}
return String(self.dropLast(suffix.count))
}
}
extension URL {
func getSuffixNumber(fileName: String, separator: String) -> Int {
let a = self.lastPathComponent.trimPrefix(fileName + separator)
if a == self.lastPathComponent {
return -1
}
let b: String
if self.pathExtension == "" {
b = a
} else {
b = a.trimSuffix("." + self.pathExtension)
}
guard let n = Int(b) else {
return -1
}
return n
}
}
func main() {
let urls: [URL] = [
URL(fileURLWithPath: "/tmp/Hello World.txt"),
URL(fileURLWithPath: "/tmp/Hello World 123.txt"),
URL(fileURLWithPath: "/tmp/Goodbye 123.txt"),
URL(fileURLWithPath: "/tmp/Hello World-456.txt"),
URL(fileURLWithPath: "/tmp/Hello World_789.txt"),
URL(fileURLWithPath: "/tmp/Hello World 777"),
URL(fileURLWithPath: "/tmp/Hello World 777/abc 123.txt"),
]
print("Number\tPath")
for url in urls {
print("\(url.getSuffixNumber(fileName: "Hello World", separator: " "))\t\(url.path)")
}
}
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment