从Groovy中的字符串中删除前缀

Mic*_*das 12 string groovy substring prefix

我需要在Groovy中从String中删除前缀,如果它真的是在开头.

如果前缀是groovy:

  • 因为groovyVersion 我期待Version
  • 因为groovy我期待空字符串
  • 因为spock我期待spock

现在我用.minus(),但是当我这样做

'library-groovy' - 'groovy'
Run Code Online (Sandbox Code Playgroud)

然后我得到了library-而不是library-groovy.

什么是实现我想要的groovy方式?

cch*_*son 22

我对Groovy不太了解,但这是我对此的看法:

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

println(str)
Run Code Online (Sandbox Code Playgroud)


Fel*_*els 9

这是区分大小写的,不使用正则表达式:

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

if (string.startsWith(prefix)) {
    result = string.substring(prefix.size())
    print result
}
Run Code Online (Sandbox Code Playgroud)


Mic*_*ter 9

这个版本简单明了,但它满足要求并且是对原始版本的增量更改:

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")
Run Code Online (Sandbox Code Playgroud)