Created
September 28, 2016 20:57
-
-
Save giacaglia/9e9c1edd32574b1083e012c4ff518aac to your computer and use it in GitHub Desktop.
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
- (nonnull NSString *)camelCaseToSnakeCaseString | |
{ | |
if ([self length] == 0) { | |
return @""; | |
} | |
NSError *error = nil; | |
// this regex finds the boundaries between lowercase/uppercase/digits and lets the string be split accordingly. | |
NSString *lowercaseToUppercaseBoundary = @"(?<=[a-z])(?=[A-Z])"; | |
NSString *lowercaseToDigitBoundary = @"(?<=[a-z])(?=[0-9])"; | |
NSString *digitToUppercaseBoundary = @"(?<=[0-9])(?=[A-Z])"; | |
NSString *regexStr = [NSString stringWithFormat:@"(%@|%@|%@)", lowercaseToUppercaseBoundary, lowercaseToDigitBoundary, digitToUppercaseBoundary]; | |
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regexStr options:0 error:&error]; | |
NSArray *pieces = [self componentsSeparatedByRegularExpression:regex]; | |
pieces = [pieces bk_map:^NSString *(NSString *str) { | |
return [str lowercaseString]; | |
}]; | |
return [pieces componentsJoinedByString:@"_"]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment