You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 07:33:52