Groovy:从文件中提取数字

时间:2013-11-12 03:14:50

标签: groovy

我有一个包含许多数字的列表:

1, 2, 3, 4, 5,
6, 7, 8, 9, 10,
...

如何逐行提取并进行一些计算? 像(伪代码)的东西:

def f = new File("data.txt")
f.eachLine() {
    println(it.findAll( /\d+/ )*.toInteger()*2)
}

我需要摆脱逗号和空白。

4 个答案:

答案 0 :(得分:1)

这个怎么样?

def fileContent = new File('data.txt').text
def matches = fileContent =~ /\d+/
matches.each {
    println new Integer(it)*2
}

给出

2
4
6
8
10
12
14
16
18
20

答案 1 :(得分:1)

这个怎么样:

file.splitEachLine(/,\s+/){
        it.each(){
                println it.replace(/,/,'').toInteger() * 2
        }
}

如果文件末尾没有逗号,则不需要替换。

答案 2 :(得分:0)

您可以使用扫描仪从文件中读取所有数据。 Here是链接

答案 3 :(得分:0)

这是一个值得帮助的人。我仍然相信可能有更好的方法:

def list = []
new File('data.txt').eachLine{
    list << it.replaceAll(/,/, '')
}

assert list*.replaceAll('\\s+', "")*.toInteger() == [12345, 678910]
//or
assert list.collect{it.replaceAll('\\s+', "").toInteger()} == [12345, 678910]