【发布时间】:2012-09-08 21:24:37
【问题描述】:
我正在尝试创建一个程序,该程序使用正则表达式从目录中读取 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,福特,E350,"ac, abs, moon",3000.00
1999,Chevy,"Venture""加长版""","",4900.00
1999,Chevy,"Venture""加长版,超大""","",5000.00
1996,吉普,大切诺基,“必须卖!
空气,月顶,装载",4799.00
我得到的输出与我的代码中的问题在哪里?为什么我的正则表达式对代码没有任何影响?
【问题讨论】:
-
“我不想使用任何现有的 CSV 库”我建议您详细说明这一点。为什么不?一般来说,Regex 是这个工作的错误工具,有很好的 CSV 解析库用于此目的。
-
String.split (docs.oracle.com/javase/1.4.2/docs/api/java/lang/String.html) 对您来说还不够吗? :)
-
@EdC 通过使用正则表达式,我试图将其扩展到其他文件格式,例如通用阅读器,通过使用不同的正则表达式,我可以解析不同的格式。顺便说一句,为什么 Regex 是错误的工具,您能详细说明一下吗?
-
@m4tx 完整的 CSV 支持比这更复杂,您必须处理引用的内容、跨多行的行和转义。
-
@niranjan-subramanian 基本上,CSV 是一种比看起来更复杂的格式,有很多边缘情况需要处理。正则表达式非常适合搜索字符串。虽然它可以用于解析,但其他工具可以更好地完成这项工作。不要说得太细,但那些 CSV 解析库是有原因的。