Remove prefix from string in Groovy

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

If the prefix is groovy:

  • for groovyVersionI expectVersion
  • for groovyI expect an empty string
  • for spockI expectspock

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

'library-groovy' - 'groovy'

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

What is the Groovy way to achieve what I want?

+4
source share
5 answers

I don't know much about Groovy, but here is my example:

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

println(str)
+5
source

This version is simple and simple, but it meets the requirements and represents a gradual change in your original:

def trimGroovy = { 
    it.startsWith('groovy') ? it - 'groovy' : it
}

assert "Version" == trimGroovy("groovyVersion")
assert "" == trimGroovy("groovy")
assert "spock" == trimGroovy("spock")
assert "library-groovy" == trimGroovy("library-groovy")
+3

, , (, , , )

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 can add this to metaClass from the line

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

then do:

assert 'library-groovy'.stripGroovy() == 'library'
+2
source

you should use regexp:

assert 'Version  spock' == 'groovyVersion groovy spock'.replaceAll( /\bgroovy/, '' )
+1
source

This case is case sensitive and does not use a regex:

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

if (string.startsWith(prefix)) {
    result = string.substring(prefix.size())
    print result
}
+1
source

Source: https://habr.com/ru/post/1652182/


All Articles