Search code examples
intellij-ideavelocity

Transform camel cased String to snake case or dash case in Velocity or IntelliJ File Template


I want to transform a camel cased string like "RoomAvailability" to a "dash cased" string like "room-availability" Velocity respectively in an IntelliJ File Template which is using Apache Velocity.

I've found dozens of posts with asking from snake case to camel case which is no problem with e. g. #set($name = ${StringUtils.removeAndHump("room_availability")}) which leads to RoomAvailability.

Another possibility would be to transform camel case to snake case and then replace '_' with '-' via #set($replaced = ${snake_cased_name("_", "-")}) but I'm also missing a possibility to transform a string to snake case.

Are there any options to do something like that in an IntelliJ File Template respectively Velocity?


Solution

  • I've found a soloution. Not quite elegant as an ready to use function, but however, it works.

    #set( $regex = "([a-z])([A-Z]+)")
    #set( $replacement = "$1-$2")
    #set( $toDash = $NAME.replaceAll($regex, $replacement).toLowerCase())
    ...
    ${toDash}
    

    Credits go to Elena Pogorelova from JetBrains for her post at enter link description here