使用groovy中的列表进行字符串比较

时间:2013-07-18 22:51:46

标签: list groovy string-comparison

我有两个列表如下:

def justNames = ["test", "test1"]
def namesWithNumber = ["test-1", "test-2", "test1-2"]

我想创建一个对列表,这样每个对在justNames中都有一个元素,在以下条件下有一个来自namesWithNumber的元素。 justNames中的元素必须与来自连字符之前的namesWithNumber的元素部分完全匹配。所以:

def pairs = [["test", "test-1"], ["test1", "test1-2"], ["test", "test-2"]]

我无法弄清楚循环列表的最佳方法是什么。在我的实际代码中,justNames非常大,而namesWithNumber则要小得多。任何人都可以建议一个groovy方式来创建对列表?如果重要或有帮助,justNames和namesWithNumber是使用正则表达式从单个列表创建的,如下所示:

def testList = ["test", "test-1", "test1", "test-2", "test1-2"]
def justNames = []
def namesWithNumber = []
testList.each {
    if (it =~ /-\d$/) {
        namesWithNumber << it
    } else {
        justNames << it
    }
}

谢谢!

1 个答案:

答案 0 :(得分:2)

[justNames, namesWithNumber].combinations().findAll{it[0] == it[1].split(/-/)[0]}