【问题标题】:Groovy replaceAll CommaGroovy 替换所有逗号
【发布时间】:2012-09-24 01:00:20
【问题描述】:

我在使用 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 不会那么难。我查看了文档,但不确定如何应用字符串、闭包组合。

【问题讨论】:

    标签: csv groovy replaceall


    【解决方案1】:

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

    也就是说,考虑一下这段代码:

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

    这会有所帮助。

    【讨论】:

    • 谢谢。我不知道我是怎么错过的。
    猜你喜欢
    • 1970-01-01
    • 2014-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-17
    • 2011-02-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多