PegasusTT77 - 10 months ago 42
Groovy Question

# return substring within an array

I found a good solution but not exactly for my problem:

String s = "abc.def.ghfj.qert";
s.substring(s.lastIndexOf(".") + 1)


Source:
Java: Getting a substring from a string starting after a particular character

This I have to use it within an array, but I have NO idea how to do... sorry.

I got the following code:

a = [];
for(i in 0..b.size()-1)
{ a[i] = b.getAt(i).toString().reverse().substring(0,1) }
total = 0
for(x in a) { total = total +","+x }
val = total.substring(2)


This is my result:

[b] = [java.util.ArrayList] [

Group:m.1:book1150:MGROUP.6/M/m.1,

Group:m.6:book1150:MGROUP.6/M/m.6,

Group:m.9:book1150:MGROUP.6/M/m.9]

[a] = [java.util.ArrayList] [1, 6, 9]

[total] = "0,1,6,9"

[val] = "1,6,9"


... but it is not practicable if my array contains a value greater than 9.

What can I do if my array is e.g.:

[b] = [java.util.ArrayList] [

Group:m.1:book1150:MGROUP.6/M/m.1,

Group:m.6:book1150:MGROUP.6/M/m.6,

Group:m.9:book1150:MGROUP.6/M/m.12]


and my result should be:

[val] = "1,6,12"


Who can help me? Where do I have to write e.g. "lastIndexOf(".")" or do anyone have a better solution?

I would recommend using regular expressions instead, and maybe some List-based mix-ins for good measure. Something like this maybe:
def b = getLinkedItems(item("link_M"))
def a = b.collect { (it.toString() =~ /\d+$/)[0] } def val = a.join(",") def total = "0," + val  In this, b.collect runs the Closure that follows once for each element of b, returning a List of results to assign to a. The find (=~) operator returns a Matcher object that finds all instances of the regular expression on the right (/\d+$/ in this case) within the source String on the left. The matched values can be retrieved from the Matcher by indexing it like a List. Then on the next line, a.join(",") joins together all the elements of a with , as a separator.
The regular expression /\d+$/ means: • \d+ any substring of one or more digits • $ at the end of the source String