Remove prefix from string in Groovy

Michal Kordas picture Michal Kordas · Aug 23, 2016 · Viewed 27.3k times · Source

I need to remove prefix from String in Groovy if it begins the string (no action otherwise).

If prefix is groovy:

  • for groovyVersion I expect Version
  • for groovy I expect empty string
  • for spock I expect spock

Right now I use .minus(), but when I do

'library-groovy' - 'groovy'

then as a result I get library- instead of library-groovy.

What's the groovy way to achieve what I want?

Answer

ccheneson picture ccheneson · Aug 23, 2016

I dont know much about Groovy but here is my take on this one:

def reg = ~/^groovy/   //Match 'groovy' if it is at the beginning of the String
String str = 'library-groovy' - reg

println(str)