Groovy中按/分隔提取第3个和最后一个子串的方法
Groovy提取路径指定子串的简便方法
在Groovy里处理这种路径分割需求,用split('/')把字符串拆分成数组是最直接简便的方式,不用手动计算分隔符位置。
完整实现代码
def productPath = "Store/Grocery/Produce/Apples" // 按斜杠分割字符串,得到子串数组 def pathSegments = productPath.split('/') // 提取第3个子串(数组索引从0开始,所以取索引2) def targetCategory = pathSegments[2] // 提取最后一个子串,Groovy支持负索引,-1直接指向最后一个元素 def targetItem = pathSegments[-1] println targetCategory // 输出 Produce println targetItem // 输出 Apples
特殊情况处理
如果路径可能存在首尾斜杠或者连续斜杠(比如"/Store//Grocery/Produce/Apples/"),可以先过滤掉空字符串,避免数组里出现空元素:
def pathSegments = productPath.split('/').findAll { it.trim() != '' }
这种方式比手动调用indexOf或lastIndexOf计算位置更直观,也不容易出错,特别适合刚接触Groovy的开发者。
内容的提问来源于stack exchange,提问作者sandsawks
相关产品推荐
相关产品推荐

