ディレクトリからCSVファイルを読み取り、正規表現を使用してファイルの各行を解析し、正規表現パターンに一致した後に行を表示するプログラムを作成しようとしています。たとえば、これが私のcsvファイルの最初の行である場合
1997,Ford,E350,"ac, abs, moon",3000.00
私の出力は
1997 Ford E350 ac, abs, moon 3000.00
既存の CSV ライブラリを使用したくありません。私は正規表現が苦手です。ネットで見つけた正規表現を使用しましたが、私のプログラムでは機能しません これは私のソース コードです。私のコードを機能させるために.Plsは私を説明します.
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年、フォード、E350、"ac、abs、moon"、3000.00
1999年、シボレー、"ベンチャー""拡張版"""、""、4900.00
1999年、シボレー、"ベンチャー""拡張版、非常に大きい"""、""、5000.00
1996年、ジープ、グランドチェロキー、「MUST SELL!
エア、ムーン ルーフ、搭載",4799.00
出力と同じ結果が得られますが、コードのどこに問題がありますか? 私の正規表現がコードに影響を与えないのはなぜですか?