【发布时间】:2010-11-29 07:39:03
【问题描述】:
我知道,现在我有两个问题。但我玩得很开心!
我从this advice 开始,不是尝试拆分,而是匹配可接受的字段,然后从那里扩展到这个表达式。
final Pattern pattern = Pattern.compile("\"([^\"]*)\"|(?<=,|^)([^,]*)(?=,|$)");
表达式看起来像这样,没有烦人的转义引号:
"([^"]*)"|(?<=,|^)([^,]*)(?=,|$)
这对我来说效果很好 - 要么匹配“两个引号以及它们之间的任何内容”,要么匹配“行首或逗号与行尾或逗号之间的某个内容”。遍历匹配项可以获得所有字段,即使它们是空的。例如,
the quick, "brown, fox jumps", over, "the",,"lazy dog"
分解成
the quick
"brown, fox jumps"
over
"the"
"lazy dog"
太棒了!现在我想删除引号,所以我添加了前瞻和后瞻非捕获组,就像我为逗号所做的那样。
final Pattern pattern = Pattern.compile("(?<=\")([^\"]*)(?=\")|(?<=,|^)([^,]*)(?=,|$)");
表达式又是:
(?<=")([^"]*)(?=")|(?<=,|^)([^,]*)(?=,|$)
而不是想要的结果
the quick
brown, fox jumps
over
the
lazy dog
现在我得到了这个细分:
the quick
"brown
fox jumps"
,over,
"the"
,,
"lazy dog"
我错过了什么?
【问题讨论】:
-
我假设您的文本本身不能包含引号?
-
谢天谢地没有。那时我只会使用 openCSV 库。
-
其他用于 Java 的 CSV 库:stackoverflow.com/questions/101100/csv-api-for-java