Joe
Joe

Reputation: 3

Substring to extract before or/and after specific character in text

I'm currently writing a groovy script that can extract characters based on the condition given, however I struggled extracting specific string after specific number of char. For example:

If (text = 'ABCDEF')
{
Return (start from C and print only CDE)
}

I already used substring but didn't give me the right output:

If (text = 'ABCDEF')
{
    Return(text.substring(2));
}

Upvotes: 0

Views: 2077

Answers (3)

King Henry
King Henry

Reputation: 416

Your substring function isn't complete. If you need to grab specific indices (in this case, index 2 to 5), you need to add the index you want to end at. If you don't do that, your string will print the string starting from index 2, and then the remaining characters in the string. You need to need to type this:

if(text == 'ABCDEF') {
   return text.substring(2, 5);
}

Also, keep in mind that the end index (index 5) is exclusive, so the character at index 5 won't be printed.

Upvotes: 0

Loïc
Loïc

Reputation: 591

Try this:

if (text == 'ABCDEF') 
{
   return text.substring(2, 5)
}

= is for assigning a value to a variable.

== is for checking equality between the two variable.

Upvotes: 1

tim_yates
tim_yates

Reputation: 171194

Your capitalization is all out of whack

if (text == 'ABCDEF') {
    text.substring(2)
}

There's probably also issues with using return, but that depends on context you haven't shown in your question

Upvotes: 0

Related Questions