Java如何仅更改字段分隔符而不更改实际数据

标签 java regex csv

我有一个输入 CSV,其中的数据用双引号括起来,字段分隔符是逗号 (,),如下所示是 3 列和 1 行:

"Id","Description","LastModifiedDate","Quantity"
"101","this is a test message - "","" how are you, where are you from","2018-01-13","15.0"
"102","this is line break msg , "2019-01-01","13.0"
 where data goes to next line"

我只想将字段分隔符从逗号 (,) 更改为脱字符号 (^),因此在从输入 CSV 读取行时我写了 line.replace("\",\"", "\"^\"") ; 低于实际结果:

"Id"^"Description"^"LastModifiedDate"
"101"^"this is a test message - ""^"" how are you, where are you from"^"2018-01-13"^"15.0"
"102"^"this is line break msg ^ "2019-01-01"^"13.0"
 where data goes to next line"

问题是使用上面的替换代码,它将所有逗号替换为我不想要的插入符号。 预期输出应如下所示:

"Id"^"Description"^"LastModifiedDate"
"101"^"this is a test message - "","" how are you, where are you from"^"2018-01-13"^"15.0"
"102"^"this is line break msg ^ "2019-01-01"^"13.0"
 where data goes to next line"

据我所知,这可以使用 Java 正则表达式来处理,但不幸的是,我不太擅长使用正则表达式,因此非常感谢任何帮助。

更新

         Regex1  : replaceAll("\",\"(?!\"\")", "\"^\"");

        Example1,
     "Id","Description","LastModifiedDate","Quantity"  -- header
     "101","hello-this,is test data"",""testing","2018-10-01","\"  -- input row1
    "101"^"hello-this,is test data""^""testing"^"2018-10-01"^"\"  -- post Regex1
     "101"^"hello-this,is test data"",""testing"^"2018-10-01"^"\"  -- expected

 In first row if data contains "","" it still gets replaced to ""^""


     Example2, 
       "Id","Description","LastModifiedDate","Quantity"  -- header 
       "102","""text in double quotes""","13.2" -- input row2
       "102","""text in double quotes"""^"13.2"  -- post with only Regex1
        "102"^""text in double quotes""^"13.2"  --  expected result

 So I tried one more regex after regex1 for second row scenario
Regex 2:  replaceAll(",\"\"\"(?!\"\")", "^\"\""); 

      regex2 along with regex1 partially worked but still, the row1 issue is not getting resolved.

是否可以在 1 个 replaceAll 或多个 replaceAll 中处理所有这些情况

最佳答案

我想这很适合你;

    text = text.replaceAll("\",\"(?!\")", "\"^\"");

\",\"(?!\") 这部分的意思是如果"\""后面没有跟着"\",下面的内容将匹配"\""。

关于Java如何仅更改字段分隔符而不更改实际数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54176212/

相关文章:

python - 正在创建的 CSV 文件大于我在 python/pycharm 中的原始数据的大小?

c# - 如何在 C# 中创建 CSV 文件

excel - 将excel一列分成两列

java - 绘制扩展 JPanel 的类

java - Java 中的数学问题;计算得出的不可思议的 NaN

Python正则表达式模式定义不包括字符

java - 标记化错误 : java. util.regex.PatternSyntaxException,悬空元字符 '*'

Java//与RegExp和方括号不匹配

java - Dijkstra算法java实现bug

java - 回调<P,R> 和函数<T,R> 之间的区别