Groovy String Extract

I'm trying to extract part of a string in Groovy. Can't seem to get the syntax right.

For example: def string = "this is a new string"
What I want is a string that says "a new string"
def string1 = string.subString(8) just gives me an error.

Can someone point me in the right direction please.

Uh "substring()" should be all lowercase?

https://www.tutorialspoint.com/groovy/groovy_substring.htm

String substring(int beginIndex)
String substring(int beginIndex, int endIndex)

Tried that. Same result.

Can you provide a section of code that this is related to?

Your code absolutely works in the online compiler..
https://www.tutorialspoint.com/execute_groovy_online.php

def string = "this is a new string"
def string1 = string.substring(8)
println(string1)

result:

$groovy main.groovy
a new string

I think I found the problem. My initial string apparently wasn’t a string. Sometimes the obvious isn’t so obvious.

Thanks for the help.

1 Like

I have been there and done that!!!! (more times than I care to admit). Sometimes you just need someone to talk it through..

2 Likes

This can be remedied by using:

String string1

instead of

def string1

You never truly know what you are getting when you use def. Fortunately you can specify.

2 Likes

It was a dateTime which I mistakenly thought was in string format. Serves me right for not checking better to start with. I was mainly just doing some experimenting with an app so it wasn't a big deal. Sure appreciate all the help.

Ah.. Well also note you can most likely do:

variable.toString().substring(8)

1 Like