0

我遇到了 Groovy 中的 replaceAll 功能的问题。
我正在处理 CSV 解析器分配,我正在尝试用空格替换逗号。我无法弄清楚实际替换它们的语法,因为每次我运行脚本时,返回的数据仍然包含逗号。

class ActAsCSV {
    def headers = []
    def contents = []     
    def read() {
        def file = new File('C:/Users/Alex/Desktop/csv.txt')
        def lines = file.readLines()
        headers = lines[0].split(",")

        def last = lines.tail()
        def i = 0
        while (last[i] != null){last[i].replaceAll(/,(?=([^\"]*\"[^\"]*\")*[^\"]*$)/' ')
           println last[i]
           i++}
        }    
}

alex = new ActAsCSV()
alex.read()

CSV 文件如下所示:年份、品牌、型号

1997,Ford,E350

2000,Mercury,Cougar

headers 数组按预期工作。当前代码之后的输出是

1997,Ford,E350
2000,Mercury,Cougar

我试过了

","

','

/','/

/,/

以及我在网上找到的各种正则表达式模式。从字面上看,没有任何效果。我不知道我错过了什么,我认为 replaceAll 不会那么难。我查看了文档,但不确定如何应用字符串、闭包组合。

4

1 回答 1

3

请注意,该replaceAll()方法返回结果字符串,而上面的代码错误地假设 last[i] 正在被修改。

也就是说,请考虑以下代码片段:

String tmp = last[i].replaceAll(/,/,' ')
println tmp

这会有所帮助。

于 2012-09-24T01:23:21.993 回答