【问题标题】:Replace quotes in String替换字符串中的引号
【发布时间】:2019-11-02 11:09:14
【问题描述】:

我必须用点替换双引号之间的所有逗号。 我正在尝试使用 replace 和 replaceAll Java 的方法来做到这一点。但是我还是没有找到解决办法。 有人可以帮我吗?

编辑: 我必须手动将 csv 文件解析为对象。所以我试图对每个输入行进行字符串拆分,但是一个数字里面有一个逗号,所以我得到的数据比拆分所需的数据多。 示例:我必须拆分此字符串。

"""LASER MEDIA SOCIETA' COOPERATIVA""",CNF146010,FM (S),PIAZZA UMBERTO I - PISTICCI,MT,40N2323,16E3328,383,,"99,1",CITY RADIO,"H: - -V: 32 dBW",0.0

请注意,我有 "99,1" 和 ,, 在这之前给我带来了麻烦。

Scanner var = new Scanner(new BufferedReader(new FileReader ("t1.csv")));
     ArrayList<Catasto> obj = new ArrayList();
     String data = var.nextLine();
     String data2 = null;
     String full = null;
     int j = 0;
     while (var.hasNextLine()) {
         data = var.nextLine();
         data2 = var.nextLine();
         full = data + data2;
         //full = full.replaceAll("\"*[,]*\"", "."); attempt 1
         System.out.println(full);
         ArrayList<String> parts = new ArrayList();
         String[] parti = full.split(",");
         //for (int i = 0; i<parti.length; i++) {  this is because I'm trying to change empty string with a null
         //if (parti[i] == " ")                    in order to solve this error: java.lang.NumberFormatException: For input string: ""
         //      parti[i] = null;                  
         //}
         for (int i = 0; i<12; i++) {
                 parts.add(parti[i]);
         }
         Catasto foo = new Catasto(parts);
         obj.add(foo);
    }
     var.close();

编辑 2: 我已经解决了双引号之间的逗号问题。但是不知道为什么会报错:java.lang.NumberFormatException: For input string: ""

【问题讨论】:

  • 您当前的解决方案遇到了什么问题?
  • 显示一些代码看看有什么问题
  • @BugsForBreakfast 在这里
  • @Lauqz 那 NumberFormatException 是因为你不能将 "" 转换为数字,必须用 "" 做点什么
  • 谢谢Bug,我解决了! :)

标签: java regex string replace


【解决方案1】:

您将很难使用单个 replaceAll 或 replace 来确定成对的引号。最好的办法是匹配成对的引号并使用 replaceAll 将组中的逗号更改为句号。

   String input = "\"One,Two,There\",\"Four,Five,Six\"";

   Matcher m = Pattern.compile("\"[^\"]*\"").matcher(input);
   StringBuffer sb = new StringBuffer();
   while(m.find()) {
       m.appendReplacement(sb, m.group().replaceAll(",", "."));
   }
   m.appendTail(sb);

   String output = sb.toString(); // "One.Two.There","Four.Five.Six"

【讨论】:

  • 谢谢你,它工作正常。你能帮我解决上面的第二个问题吗?我真的很挣扎
猜你喜欢
  • 2022-11-17
  • 1970-01-01
  • 1970-01-01
  • 2023-03-23
  • 2012-03-12
  • 1970-01-01
  • 1970-01-01
  • 2011-12-07
相关资源
最近更新 更多