Phoenix
Phoenix

Reputation: 8923

How to add a prefix to a groovy string?

I have a string that contains IPCM_20120223_xml.tar.gz and i want to change it to USLF_20120223_xml.tar.gz How can I change only the prefix from IPCM to USLF ?

Upvotes: 2

Views: 1973

Answers (2)

sbglasius
sbglasius

Reputation: 3124

def inital = "IPCM_20120223_xml.tar.gz"

def result3 = 'USLF'+inital-'IPCM'
assert "USLF_20120223_xml.tar.gz" == result3

Upvotes: 0

Jarred Olson
Jarred Olson

Reputation: 3243

Here is 2 ways to do it.

    def inital = "IPCM_20120223_xml.tar.gz"

    def result1 = inital.replaceFirst("IPCM_", "USLF_")
    def result2 = "USLF${inital.substring(4)}"

    assert "USLF_20120223_xml.tar.gz" == result1
    assert "USLF_20120223_xml.tar.gz" == result2

Depending on what generates the initial name for you you may want one over the other.

First way would be good if you know it always starts with "IPCM_" and that character sequence is never anywhere but on the front.

Second way would be good if you know it always starts with a 4 letter sequence and you don't care what it is but you want to change it to USLF.

Upvotes: 5

Related Questions