Groovy list indexof

If I have a list with the following items

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

How to find the index where the line begins with SELECT.

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

But this is a dynamic list. SELECT somethingusually will not SELECT something. it can be SELECT somethingelseor whatever, but the first word will always be SELECT.

Is there a way to apply regex to indexOf search?

+5
source share
2 answers

You can use 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"
+5
source
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 element that matches the regular expression /SELECT \w+/. If you want to get the indices of all matching elements, replace the second line with

def index = list.findIndexValues { it ==~ /SELECT \w+/ }
+15
source

All Articles