简体   繁体   中英

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?

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)

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).

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?

你应该使用正则表达式:

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 */

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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