3

I have a bunch of string properties in a gradle build script, which is in camelCase (for example "jmxConsoleWeb"), and I'd like to split each into a dash-separated (e.g. jmx-console-web) string instead.

Is there a "non-hackish" way to do this?

2 Answers 2

8

I've solved it like this:

public static String dashSeparated(String s) { 
     return s.replaceAll(/\B[A-Z]/) { '-' + it }.toLowerCase() 
}

Also take a look here

2
  • That's good enough for my purposes. I tried figuring out how to use the built-in (?) utility classes that the linked forum thread referred to, but I couldn't figure out exactly which one I needed so I just added this directly to my build script. Jun 11, 2013 at 12:36
  • I don't know build-in way. If anybody knows tell us (=
    – Mr. Cat
    Jun 11, 2013 at 12:42
8

You can use Guava if you don't mind the extra dependancy. Here's a Groovy script that demonstrates its use:

@Grab( 'com.google.guava:guava:13.0.1' )
import static com.google.common.base.CaseFormat.*

String.metaClass.caseFormat = { from, to ->
  from.to( to, delegate )
}

assert 'varName'.caseFormat( LOWER_CAMEL, UPPER_UNDERSCORE )       == 'VAR_NAME'
assert 'var-name'.caseFormat( LOWER_HYPHEN, UPPER_CAMEL )          == 'VarName'
assert 'var_name'.caseFormat( LOWER_UNDERSCORE, LOWER_CAMEL )      == 'varName'
assert 'VAR_NAME'.caseFormat( UPPER_UNDERSCORE, LOWER_UNDERSCORE ) == 'var_name'
assert 'VarName'.caseFormat( UPPER_CAMEL, LOWER_HYPHEN )           == 'var-name'

Of course, in a Gradle script, you'd need to import guava into the buildScript dependencies if you want its methods available to the build itself

1
  • +1 Good Information Tim. Any reason why the former approach or alike has not been implemented in-built for Groovy String for camelCase yet?
    – dmahapatro
    Jun 11, 2013 at 20:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.