Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

groovy list indexOf

Tags:

regex

groovy

If I have a list with following elements

list[0] = "blach blah blah"
list[1] = "SELECT something"
list[2] = "some more text"
list[3] = "some more text"

How can I find the index of where the string starts with SELECT.

I can do list.indexOf("SELECT something");

But this is a dynamic list. SELECT something wont always be SELECT something. it could be SELECT somethingelse or anything but first word will always be SELECT.

Is there a way to apply regex to the indexOf search?

like image 570
Omnipresent Avatar asked Oct 08 '09 21:10

Omnipresent


2 Answers

def list = ["blach blah blah", "SELECT something", "some more text", "some more text"]
def index = list.findIndexOf { it ==~ /SELECT \w+/ }

This will return the index of the first item that matches the regex /SELECT \w+/. If you want to obtain the indices of all matching items replace the second line with

def index = list.findIndexValues { it ==~ /SELECT \w+/ }
like image 58
Dónal Avatar answered Nov 13 '22 09:11

Dónal


You can use a regex in find:

def list = ["blach blah blah", "SELECT something", "some more text", "some more text"]

def item = list.find { it ==~ /SELECT \w+/ }

assert item == "SELECT something"

list[1] = "SELECT somethingelse"

item = list.find { it ==~ /SELECT \w+/ }

assert item == "SELECT somethingelse"
like image 27
John Wagenleitner Avatar answered Nov 13 '22 10:11

John Wagenleitner