正则表达式在数组中使用小数和数字的混合 [英] Regex using mix of decimals and numbers in an array
本文介绍了正则表达式在数组中使用小数和数字的混合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
正在努力寻找一种方法来乘以下面数组中的数字
Struggling to find a way to multiply the numbers in the below array
[120.98 7, 151.99 8, 141.39 4, 137.71 7, 121.27 6, 187.29 11]
尝试使用split按空间拆分它们,然后将它们相乘,但是遇到问题,有什么想法吗?
Trying to split them by space using split and multiply them however facing issues, any ideas ?
要求将两个数字乘以逗号.
Ask is to multiply the two numbers before comma.
推荐答案
如果您的数组如您所展示的那样站立,那就是一个问题.但是,如果您首先以String格式设置它,这是一个解决方案:
It's a problem if your array stands as you show it. But if you set it first in String format, here is a solution :
myArray = "[120.98 7, 151.99 8, 141.39 4, 137.71 7, 121.27 6, 187.29 11]"
myStr = myArray[2..-1] // to get rid of brackets
myStr = myStr[0..-2]
myStr = myStr.tokenize('[,]') // for parsing
println myStr
myStr.each{
//println it
first = it.split()[0].toDouble()
second = it.split()[1].toDouble()
println "$first * $second = " + first*second
}
这可能不是最好或最干净的方法,但它符合您的要求 结果如下:
It's probably not the best or cleanest way, but it fits your requirements here's the result:
[20.98 7, 151.99 8, 141.39 4, 137.71 7, 121.27 6, 187.29 11]
20.98 * 7.0 = 146.86
151.99 * 8.0 = 1215.92
141.39 * 4.0 = 565.56
137.71 * 7.0 = 963.97
121.27 * 6.0 = 727.62
187.29 * 11.0 = 2060.19
亚历克斯
这篇关于正则表达式在数组中使用小数和数字的混合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文