Findall与字符串groovy数组

问题描述 投票:2回答:3

我有一个字符串/sample/data。当我使用split分割时,我得到以下结果,

["","sample","data"]

我想忽略空字符串。所以我尝试了以下代码,

"/sample/data".split('/').findAll(it != "")

它给了我一个错误“cannot call String[] findAll with argument bool”。

如何分割并获取没有空字符串的List?

groovy split findall
3个回答
1
投票

你可以这样做:

println "/sample/data".split('/').findAll {it}

findAll {it}将获取所有非空值。


3
投票

split方法返回数组。如果需要List,请使用tokenize

"/sample/data".tokenize('/')

在这种情况下你也不需要使用findAll。


1
投票

Parens会工作(见问题评论)。所以你的解决方案已经接近了:

"/a/b".split("/").findAll()

因为大多数Groovy函数都具有零arity,它将使用标识闭包调用该函数。由于空字符串被认为是假的,因此会将其过滤掉。

© www.soinside.com 2019 - 2024. All rights reserved.