Skip to content

Instantly share code, notes, and snippets.

@pavermakov
Forked from dmsl1805/SnakeCase.swift
Last active May 6, 2021 09:20
Show Gist options
  • Save pavermakov/55a9b9065a9aea587452359314ff865e to your computer and use it in GitHub Desktop.
Save pavermakov/55a9b9065a9aea587452359314ff865e to your computer and use it in GitHub Desktop.
Camel case to snake case in Swift
extension String {
func camelCaseToSnakeCase() -> String {
let acronymPattern = "([A-Z]+)([A-Z][a-z]|[0-9])"
let normalPattern = "([a-z0-9])([A-Z])"
return self.processCamalCaseRegex(pattern: acronymPattern)?
.processCamalCaseRegex(pattern: normalPattern)?.lowercased() ?? self.lowercased()
}
fileprivate func processCamalCaseRegex(pattern: String) -> String? {
let regex = try? NSRegularExpression(pattern: pattern, options: [])
let range = NSRange(location: 0, length: count)
return regex?.stringByReplacingMatches(in: self, options: [], range: range, withTemplate: "$1_$2")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment