Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove prefix from string in Groovy

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?

like image 404
Michal Kordas Avatar asked Aug 23 '16 11:08

Michal Kordas


2 Answers

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)
like image 128
ccheneson Avatar answered Sep 29 '22 06:09

ccheneson


This is case sensitive and doesn't use a regular expression:

​def prefix = 'Groovy';
def string = 'Groovy1234';
def result = '';

if (string.startsWith(prefix)) {
    result = string.substring(prefix.size())
    print result
}
like image 29
Fels Avatar answered Sep 29 '22 06:09

Fels