cancel
Showing results for 
Search instead for 
Did you mean: 

Manipulate a string in groovy script

Robert_d_Hoedt
Explorer
0 Kudos
657

Hi,

For my Integration Suite scenario i must manipulate a string.

My input is something like: "URL.something.com/string1/string2".

The URL.something might change over time (and can be longer or shorter) and the string1/string2 can also change

The only part i can be sure of is ".com/"

What i need is a Groovy script that will take URL.something.com and replace string1/string2 with something like /mystring/ourstring.

Because of the flexible length of URL.something it is not possible to replace after a fixed length. And i can also not replace on the basis of string1/string2 because that can also change.

So it needs to be some instruction like: remove everything that comes after ".com/" and then add /mystring/ourstring.

Hopefully someone can help me out.

Kr

Robert

Accepted Solutions (1)

Accepted Solutions (1)

Robert_d_Hoedt
Explorer
0 Kudos

Hi all,

So i found something that will work independent of the length of the string

(so it will work for "https://shorturl.com/stringA" and for https://veryverylongurl.com/string A)

First action is to determine what the index of the 3rd "/" is.

Second action is take substring from 0 to index

Third action is to add customstring as a path.

String ServerURL;

static int ordinalIndexOf(String str, String substr, int n) {

int pos = str.indexOf(substr);

while (--n > 0 && pos != -1)

pos = str.indexOf(substr, pos + 1);

return pos;

}

index = ordinalIndexOf(ServerURL,'/',3);

ServerURL = (ServerURL.substring(0,index)+"/addcustomstringasapath");

kr

Robert

Answers (1)

Answers (1)

Jwan_
Explorer

Do you mean something like this?

def inputUrl = "URL.something.com/string1/string2"
def pattern = /(\.com\/)(.+)/ def matcher = (inputUrl =~ pattern) if (matcher.find()) { def modifiedUrl = matcher.group(1) + "mystring/ourstring" println modifiedUrl } else { println "Pattern not found in the URL" }
Robert_d_Hoedt
Explorer
0 Kudos

Hi Jwan,

Thx for your answer. I ran the code in www.jdoodle.com/execute-groovy-online/

The output was ".com/mystring/ourstring"

But this is not the desired outcome unfortunately.

The outcome should be "URL.something.com/mystring/ourstring"

regards

Robert

Robert_d_Hoedt
Explorer
0 Kudos

Hi Jwan,

I think i found something that might work; its called ordinalIndex

serverurl = "https://url.something.com/mystring1/mystring2"

index = ordinalIndexOf(serverurl,'/',3)

println(serverurl.substring(0,index)+""/mystring/ourstring"");

static int ordinalIndexOf(String str, String substr, int n) {

int pos = str.indexOf(substr);

while (--n > 0 && pos != -1)

pos = str.indexOf(substr, pos + 1);

return pos;

}