简体   繁体   English

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

[英]Remove prefix from string in Groovy

I need to remove prefix from String in Groovy if it begins the string (no action otherwise).如果字符串开始,我需要从 Groovy 中的字符串中删除前缀(否则不执行任何操作)。

If prefix is groovy :如果前缀是groovy

  • for groovyVersion I expect Version对于groovyVersion我期望Version
  • for groovy I expect empty string对于groovy我期望空字符串
  • for spock I expect spock对于spock我期待spock

Right now I use .minus() , but when I do现在我使用.minus() ,但是当我这样做时

'library-groovy' - 'groovy'

then as a result I get library- instead of library-groovy .然后结果我得到library-而不是library-groovy

What's the groovy way to achieve what I want?实现我想要的东西的常规方法是什么?

I dont know much about Groovy but here is my take on this one:我不太了解 Groovy,但这是我对这个的看法:

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

println(str)

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
}

This version is plain and simple, but it meets the requirements and is an incremental change to 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")

I need to remove prefix from String in Groovy if it begins the string (no action otherwise).如果Groovy中以字符串开头,则需要从String中删除前缀(否则不执行任何操作)。

If prefix is groovy :如果前缀是groovy

  • for groovyVersion I expect Version对于groovyVersion我期望Version
  • for groovy I expect empty string对于groovy我期望空字符串
  • for spock I expect spock对于spock我希望spock

Right now I use .minus() , but when I do现在我使用.minus() ,但是当我这样做时

'library-groovy' - 'groovy'

then as a result I get library- instead of library-groovy .结果我得到了library-而不是library-groovy

What's the groovy way to achieve what I want?实现我想要的目标的常规方法是什么?

你应该使用正则表达式:

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

Solution: use - opreator and cut the right string.解决方案:使用-运算符并剪切正确的字符串。

def sentence = "remove_me_i_am_ok"
def string_to_be_remove = "remove_me_"

String result = sentence - string_to_be_remove
print("output: ${result}")​

/* output: i_am_ok */

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM