簡體   English   中英

在Java中使用Regex解析CSV文件

[英]Parsing CSV files using Regex in Java

我正在嘗試創建一個程序,該程序使用正則表達式從目錄中讀取CSV文件,它解析文件的每一行並在匹配正則表達式模式后顯示這些行。 例如,如果這是我的csv文件的第一行

1997,Ford,E350,"ac, abs, moon",3000.00

我的輸出應該是

1997 Ford E350 ac, abs, moon 3000.00

我不想使用任何現有的CSV庫。 我不擅長正則表達式,我使用了在網上找到的正則表達式,但不適用於我的程序。這是我的源代碼,如果有人告訴我要在哪里修改內容,我將不勝感激。為了使我的代碼正常工作,請向我解釋。

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.CharBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.util.regex.Pattern;
import java.util.regex.Matcher;


public class RegexParser {

private static Charset charset = Charset.forName("UTF-8");
private static CharsetDecoder decoder = charset.newDecoder();
String pattern = "\"([^\"]*)\"|(?<=,|^)([^,]*)(?=,|$)";

void regexparser( CharBuffer cb)
{ 
    Pattern linePattern = Pattern.compile(".*\r?\n");
    Pattern csvpat = Pattern.compile(pattern);
    Matcher lm = linePattern.matcher(cb);
    Matcher pm = null;

    while(lm.find())
    {   
        CharSequence cs = lm.group();
        if (pm==null)
            pm = csvpat.matcher(cs);
            else
                pm.reset(cs);
        if(pm.find())
                     {

            System.out.println( cs);
                      }
        if (lm.end() == cb.limit())
        break;

        }

    }

public static void main(String[] args) throws IOException {
    RegexParser rp = new RegexParser();
    String folder = "Desktop/sample";
    File dir = new File(folder);
    File[] files = dir.listFiles();
    for( File entry: files)
    {
        FileInputStream fin = new FileInputStream(entry);
        FileChannel channel = fin.getChannel();
        int cs = (int) channel.size();
        MappedByteBuffer mbb = channel.map(FileChannel.MapMode.READ_ONLY, 0, cs);
        CharBuffer cb = decoder.decode(mbb);
        rp.regexparser(cb);
        fin.close();

    }




}

  }

這是我的輸入文件

年,制造,型號,描述,價格

1997,Ford,E350,“ ac,abs,moon”,3000.00

1999年,雪佛蘭,“冒險”,“擴展版”,“”,4900.00

1999,Chevy,“ Venture”“擴展版,非常大”“”,“”,5000.00

1996年,吉普車,大切諾基,“必須賣!

空氣,天窗,滿載”,4799.00

我得到的輸出與我的代碼中的問題相同? 為什么我的正則表達式對代碼沒有任何影響?

使用regexp似乎“花哨”,但是使用CSV文件(至少在我看來)是不值得的。 對於我的解析,我使用http://commons.apache.org/csv/ 它從來沒有讓我失望。 :)

無論如何,我自己都找到了解決方案,謝謝大家的建議和幫助。

這是我的初始代碼

    if(pm.find()
        System.out.println( cs);

現在將其更改為

  while(pm.find()
  {
 CharSequence css = pm.group();
 //print css
   }

我也使用了不同的正則表達式。 我現在得到所需的輸出。

您可以嘗試使用以下代碼: [ \\t]*+"[^"\\r\\n]*+"[ \\t]*+|[^,\\r\\n]*+

try {
    Pattern regex = Pattern.compile("[ \t]*+\"[^\"\r\n]*+\"[ \t]*+|[^,\r\n]*+", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE | Pattern.MULTILINE);
    Matcher matcher = regex.matcher(subjectString);
    while (matcher.find()) {
        // Do actions
    } 
} catch (PatternSyntaxException ex) {
    // Take care of errors
}

但是,是的,如果不是非常關鍵的需求,請嘗試使用已經有效的方法:)

請遵循提供的建議,不要使用正則表達式來解析CSV文件。 該格式在使用方式上看似復雜。

以下答案包含指向Wikipedia和描述CSV文件格式的RFC的鏈接:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM