Michal Kordas Michal Kordas - 3 months ago 8
Groovy Question

Remove prefix from string in Groovy

I need to remove prefix from String in Groovy if it really is at the beginning.

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

You could do this, but I doubt it catches all of your requirements (as I guess you have others you haven't specified here)

def tests = [
    [input:'groovyVersion',  expected:'Version'],
    [input:'groovy',         expected:''],
    [input:'spock',          expected:'spock'],
    [input:'library-groovy', expected:'library'],
    [input:'a-groovy-b',     expected:'ab'],
    [input:'groovy-library', expected:'library']
]

tests.each {
    assert it.input.replaceAll(/\W?groovy\W?/, '') == it.expected
}

You could add this to the metaClass of String

String.metaClass.stripGroovy = { -> delegate.replaceAll(/\W?groovy\W?/, '') }

then do:

assert 'library-groovy'.stripGroovy() == 'library'