-
-
Save two7sclash-zz/c3835d83695b46ca2a6a4b6d71272538 to your computer and use it in GitHub Desktop.
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") |
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 using it
, and why the Object[]
before it? (I'm fairly new to Groovy and come from Ruby background)
...
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.
snake case should also take into account spaces, println toSnakeCase("Camel Case Class") actually generates camel _case _class