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?

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

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


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


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.


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:


1 Like