我对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文件如下所示: Year、Make、Model
1997,Ford,E350
2000,Mercury,Cougarheaders数组按照它应该的方式工作。当前代码后的输出为
1997,Ford,E350
2000,Mercury,Cougar我试过了
,“
',‘
/','/
/,/
以及我在网上找到的各种regexp模式。从字面上看,什么都没有起作用。我不知道我错过了什么,我以为replaceAll不会这么难。我已经看过文档了,但不确定如何应用字符串、闭包组合。
发布于 2012-09-24 09:23:22
注意,replaceAll()方法返回结果字符串,而上面的代码错误地假设lasti正在被修改。
也就是说,考虑下面的代码片段:
String tmp = last[i].replaceAll(/,/,' ')
println tmp这将会有所帮助。
https://stackoverflow.com/questions/12557637
复制相似问题