Forked from avdgaag/Ruby regular expression for CamelCase and snake_case.rb
Created
November 25, 2024 11:11
-
-
Save influx6/1339b3a839317e76fa953e8892ef1301 to your computer and use it in GitHub Desktop.
Example regular expressions for converting strings to CamelCase or snake_case
This file contains hidden or 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