Created
January 19, 2009 09:40
-
-
Save avdgaag/48937 to your computer and use it in GitHub Desktop.
Example regular expressions for converting strings to CamelCase or snake_case
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
original = 'ThisIsAStringInCamelCaseWithNumbersLike12And14' | |
# Convert a CamelCase string to snake_case | |
snake_case = original.gsub(/([\w^_](?=[A-Z]))|([a-z](?=\d+))/, '\1\2_').downcase | |
# Convert a snake_case string to CamelCase | |
camel_case = snake_case.gsub(/^\w|_\w/) { |match| match[-1,1].upcase } | |
puts snake_case # => "this_is_a_string_in_camel_case_with_numbers_like_12_and_14" | |
puts camel_case # => "ThisIsAStringInCamelCaseWithNumbersLike12And14" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment