Created
November 29, 2016 19:39
-
-
Save two7sclash-zz/c3835d83695b46ca2a6a4b6d71272538 to your computer and use it in GitHub Desktop.
Groovy Convert To Camel Case 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
static String toCamelCase( String text, boolean capitalized = false ) { | |
text = text.replaceAll( "(_)([A-Za-z0-9])", { Object[] it -> it[2].toUpperCase() } ) | |
return capitalized ? capitalize(text) : text | |
} | |
static String toSnakeCase( String text ) { | |
text.replaceAll( /([A-Z])/, /_$1/ ).toLowerCase().replaceAll( /^_/, '' ) | |
} | |
println toCamelCase("some_field_name") | |
println() | |
println toSnakeCase("CamelCaseClass") |
...
it
would appear to be a charSequence of the required string but there doesn't seem to me to be an obvious connection to what we wish to pass in as is usually the case with usingit
, and why theObject[]
before it?
In partial answer to my own questions the Object[]
bit seems redundant as it still works without it. But I can find no documentation on the use of it
relating to regexp groups, all references seem to be in relation to iterators.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I was trying to do something similar and had a line of the form:-
text.replaceAll( /(\s[a-z])/ , $1.toUpperCase() )
which didn't work as the
$1
was being handled literally by the.toUpperCase
. I tried using a closure but couldn't work out how to get the$1
passed into the closure, which is what you have done. However, I'm not sure I quite understand how it works.it
would appear to be a charSequence of the required string but there doesn't seem to me to be an obvious connection to what we wish to pass in as is usually the case with usingit
, and why theObject[]
before it? (I'm fairly new to Groovy and come from Ruby background)