Saltar al contenido

~ / archivo / stackoverflow / 1540713

groovy list indexOf

StackOverflow · regex, groovy · ayudé
  1. Omnipresent pregunta +9 2009-10-08 21:53

    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?

    • bgw 2009-10-08 22:07 I would stray away from RegEx in java for performance issues, but take a look at java.sun.com/docs/books/tutorial/essential/regex . Off the top of my head, I don't think there is a simple way of doing this, except manually iterating through your array.
  2. John Wagenleitner respuesta aceptada +6 2009-10-09 00:16

    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"
    
  3. Dónal respuesta +25 2009-10-09 13:38
    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+/ }
    
  4. Miguel Ortiz yo respuesta 2024-07-29 17:37

    Another alternative:

    def test = ["A","B","C"]
    def boo = "X"
    
    test.add(test.findIndexOf{ it == "B" }, boo)
    
    println "${test}"
    

    Result: [A, X, B, C]

← todos los hilos de StackOverflow