-
-
Save pavermakov/55a9b9065a9aea587452359314ff865e to your computer and use it in GitHub Desktop.
Camel case to snake case in Swift
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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