在Groovy中拆分字符串的惯用方式 [英] Idiomatic way to split string in Groovy
本文介绍了在Groovy中拆分字符串的惯用方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有更好/更短/更好的方式来执行以下操作:
Is there a nicer/shorter/better way of performing the following:
filename = "AA_BB_CC_DD_EE_FF.xyz"
parts = filename.split("_")
packageName = "${parts[0]}_${parts[1]}_${parts[2]}_${parts[3]}"
//packageName == "AA_BB_CC_DD"
格式保持不变(6个部分,_分隔符),但AA,BB的某些值和长度是可变的.
The format remains constant (6 parts, _ separator) but some of the values and lengths of AA,BB are variable.
推荐答案
您可以通过对"joining"部分进行不同的编程来做相同的事情:
You can do the same thing by just programming the "joining" part differently:
以下结果与packageName
相同:
filename.split('_')[0..3].join('_')
它仅使用一个范围来对数组进行切片,而.join
则使用定界符进行连接.
It just uses a range to slice the array, and .join
to concatenate with a delimiter.
这篇关于在Groovy中拆分字符串的惯用方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文