【问题标题】:Java: Remove a semicolon in a string only if its after a word and quotation markJava:只有在单词和引号之后才删除字符串中的分号
【发布时间】:2016-07-29 15:00:06
【问题描述】:

这是我的问题:

我需要删除字符串中的分号,但此字符串来自 excel 中的分号分隔文件。

只有在单词后面有引号时才需要替换分号。

即: data1;data2;"This is a duck;";data3;"Here's another duck";

需要替换为:

data1;data2;"This is a duck";data3;"Here's another duck";

最好的方法是什么?

编辑:这是我尝试过的:

String line = myLine;
line.replaceAll(("\\w*;"),$1);

但我不能让它工作,我不认为这是最好的方法。我也试过了

line = line.replaceall(";\"", "\"");

但这不起作用,因为它取代了

data1;data2;"This is a duck;";data3;"Here's another duck";

data1;data2"This is a duck";data3"Here's another duck";

【问题讨论】:

  • 您自己尝试过什么,还是只是希望我们为您编写代码?
  • 是的,我正要说,请上传您的代码以便我们检查
  • 我投票决定以基于意见的方式结束此内容。这样做(或任何事情)的“最佳”方式很大程度上取决于您的观点。

标签: java regex csv


【解决方案1】:

如果你只想要正则表达式:

public static void main (String[] args) throws java.lang.Exception
    {
       Pattern p = Pattern.compile ( "\"(.*);\"");
       String input1 =  "\"This is duck;\"";
       String input2 = "This is duck;";
       Matcher m = p.matcher(input1);
       if ( m.find() )
       {
           input1 = m.group(1);
           System.out.println( "Modified input1 is : " + input1 );
       }
       else
       {
          System.out.println( "input1 is not modified" );
       }
       m = p.matcher(input2);
       if ( m.find() )
       {
           input2 = m.group(1);
           System.out.println( "Modified input2 is : " + input2 );
       }
       else
       {
          System.out.println( "input2 is not modified" );
       }
    }

输出:

Modified input1 is : This is duck
input2 is not modified

【讨论】:

    【解决方案2】:

    可能不是最好但最简单的方法:

     String str = "\"This is a duck;\"";
            str = str.replace(";\"", "\"")
    

    【讨论】:

      【解决方案3】:

      您不应该为此使用正则表达式。您应该使用 csv 解析器和写入器。

      例如,以下是使用 OpenCSV 的方法:

      CSVReader reader = new CSVReader(new FileReader("myCsv.csv"),';');
      CSVWriter writer = new CSVWriter(new FileWriter("corrected.csv"), ';');
      
      String[] lineTokens;
      
      while ((lineTokens = reader.readNext()) != null) {
          for(String token : lineTokens) {
              token.replace(";", "");
          }
      
          writer.writeNext(lineTokens);
      }
      
      writer.close();
      

      如果您需要对 csv 进行操作,请使用正确的工具。帮助自己并使用 csv 解析器。

      【讨论】:

        【解决方案4】:

        将正则表达式与positive lookahead assertion 一起使用

        /;(?=")/g
        

        例子:

        String pattern = ";(?=\")";
        String updated = STRING.replaceAll(pattern, "");
        

        String pattern = ";\"";
        String updated = STRING.replaceAll(pattern, "\"");
        

        【讨论】:

        • 这是 Java 吗? OP提到了Java。
        猜你喜欢
        • 2013-06-01
        • 1970-01-01
        • 2015-11-04
        • 2015-09-14
        • 2021-02-26
        • 2016-05-20
        • 2017-06-18
        • 2020-02-14
        • 1970-01-01
        相关资源
        最近更新 更多