简体   繁体   English

我如何使用Groovy中的块将字符串替换为增量值?

[英]How i could replace a string by incremental value using a block in groovy?

I'm trying to learn how I could use groovy I know ruby 我正在尝试学习如何使用Groovy我知道红宝石

and I use this code for replace a string by incremental value 我用这段代码用增量值替换字符串

 o=0
puts "n,n,n,n,n,n,n,n".gsub(/n/) { o+=1; "#{o}"  } 

for obtain this 1,2,3,4,5,6,7,8 获得这个1,2,3,4,5,6,7,8

How I could do this in groovy? 我如何才能做到这一点?

You can do it almost the same: 您可以执行几乎相同的操作:

def o=0
println 'n,n,n,n,n,n,n,n'.replaceAll(/n/) { ++o }

If you just want 8 consecutive comma-separated numbers you can also simply do 如果您只想要8个连续的逗号分隔数字,也可以简单地执行

println((1..8).join(','))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM