如果我有一个包含以下元素的列表
list[0] = "blach blah blah"
list[1] = "SELECT something"
list[2] = "some more text"
list[3] = "some more text"
如何找到以 SELECT 开头的字符串的索引。
我可以做
list.indexOf("SELECT something");
但这是一个动态列表。
SELECT something
不会永远是SELECT something
。它可以是 SELECT somethingelse
或任何东西,但第一个单词永远是 SELECT
。
有没有办法将正则表达式应用于索引搜索?
def list = ["blach blah blah", "SELECT something", "some more text", "some more text"]
def index = list.findIndexOf { it ==~ /SELECT \w+/ }
这将返回与正则表达式
/SELECT \w+/
匹配的第一个项目的索引。如果您想获取all匹配项的索引,请将第二行替换为
def index = list.findIndexValues { it ==~ /SELECT \w+/ }
您可以在查找中使用正则表达式:
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"
另一种选择:
def test = ["A","B","C"]
def boo = "X"
test.add(test.findIndexOf{ it == "B" }, boo)
println "${test}"
结果:
[A, X, B, C]