如果我有两个String列表,如下所示,并希望根据startsWith
逻辑创建一个新的String列表,我该怎么办?
pathList = ["/etc/passwd/something.txt",
"/etc/fonts/fonts.conf"
"/var/www/foo.bar",
"/some/foo/path/one.txt"]
notAllowedPathList = ["/etc/fonts",
"/var",
"/path"]
newList = ["/etc/passwd/something.txt", "/some/foo/path/one.txt"]
newList
是通过查看pathList
中每个元素startsWith
newList
中的每个元素来创建的。
因此,从上面的pathList
,/etc/fonts/fonts.conf
和/var/www/foo.bar
被删除,因为它们分别与/etc/fonts
和/var
开始。
我想出了下面的内容,但我相信会有一种更加时髦的方式:
def newList = []
pathList.each {String fileName ->
notAllowedPathList.find { String notAllowed ->
if (fileName.startsWith(notAllowed)) {
return true
}
else {
newList << fileName
}
}
}
答案 0 :(得分:0)
def pathList = [
"/etc/passwd/something.txt",
"/etc/fonts/fonts.conf",
"/var/www/foo.bar",
"/some/foo/path/one.txt"
]
def notAllowedPathList = ["/etc/fonts", "/var", "/path"]
def newList = pathList.findAll { String fileName ->
!notAllowedPathList.any {
fileName.startsWith(it)
}
}