Search code examples
csvgroovyreplaceall

Groovy replaceAll Comma


I'm having issues with the replaceAll feature in Groovy.
I'm working on a CSV parser assignment, and I'm trying to replace commas with spaces. I cannot figure out the syntax to actually replace them, as every time I run the script the data is returned with the commas still included.

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()

The CSV file looks like this: Year,Make,Model

1997,Ford,E350

2000,Mercury,Cougar

The headers array works as it is supposed to. The output after the current code is

1997,Ford,E350
2000,Mercury,Cougar

I have tried

","

','

/','/

/,/

and various regexp patterns I have found online. Literally nothing has worked. I don't know what I am missing, I assumed replaceAll wouldn't be this hard. I have looked over the documentation, but am unsure how to apply a string, closure combo.


Solution

  • Note that the replaceAll() method returns the resulting string, whereas the code above falsely assumes that last[i] is being modified.

    That said, consider this code fragment:

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

    This will help.