可能重复: 在java中使用RegEx解析CSV输入
我有一个输入文件,其中每一行都有以下形式的字符串的输入值:
" ab cd " , " efgh,ijk.", 4,"lmno"即
这些单词要么用引号,要么没有引号。 分别在开始和结束字之前和之后的空格是不允许的。编辑:3。它可以用逗号分隔输入。( abc,"Hi Mary,Joe",5 )
在java中使用.Split(),我需要一个正则表达式来输出:
ab cd efgh,ijk. 4 lmno我试过这个:
[^",]*[\",]但这对"efgh,ijk."无效"efgh,ijk."
以下是正则表达式测试的链接: http : //regexpal.com/我需要一些帮助。 请帮忙。 谢谢
Possible Duplicate: Parsing CSV input with a RegEx in java
I have an input file in which each line has input values of string of the following form:
" ab cd " , " efgh,ijk.", 4,"lmno"i.e.,
The words are either in quotes or they have no quotes. The space before and after the start and end word respectively is not allowed.EDIT: 3. It can have inputs just separated by commas.(abc,"Hi Mary,Joe",5)
Using .Split() in java, I need a regular expression to output this:
ab cd efgh,ijk. 4 lmnoI tried this:
[^",]*[\",]But this doesn't work on "efgh,ijk."
Here is a link for regex testing: http://regexpal.com/ I need some assistance on this. Please help. Thank you
最满意答案
DEMO
正则表达式: (?:\s*(?:\"([^\"]*)\"|([^,]+))\s*,?)+?
更新空值: (?:\s*(?:\"([^\"]*)\"|([^,]+))\s*,?|(?<=,)(),?)+? DEMO
它工作的一个例子,我知道它有点像CSV格式,但只要你不写真的很奇怪的事情,它将匹配所有这些。
Matcher ma = Pattern.compile("(?:\\s*(?:\\\"([^\\\"]*)\\\"|([^,]+))\\s*,?)+?").matcher(" \" ab cd \" , \" efgh,ijk.\", 4,\"lmno\""); while (ma.find()) { if (ma.group(1) == null) { System.out.println(ma.group(2)); } else { System.out.println(ma.group(1)); } }编辑,顺便说一句,如果你想让我们为你提供代码,不要告诉我们关于正则表达式在线测试人员,如果你这样做是因为你知道如何处理正则表达式,如果你不知道怎么做,请问它也。
DEMO
Regex pattern: (?:\s*(?:\"([^\"]*)\"|([^,]+))\s*,?)+?
Update for null values: (?:\s*(?:\"([^\"]*)\"|([^,]+))\s*,?|(?<=,)(),?)+? DEMO
An example of it working, I know it's kinda CSV Format but as long as you dont write really really weird things it'll match all of them.
Matcher ma = Pattern.compile("(?:\\s*(?:\\\"([^\\\"]*)\\\"|([^,]+))\\s*,?)+?").matcher(" \" ab cd \" , \" efgh,ijk.\", 4,\"lmno\""); while (ma.find()) { if (ma.group(1) == null) { System.out.println(ma.group(2)); } else { System.out.println(ma.group(1)); } }Edit, btw if you wanted us to give the code for you, don't tell us about a regex online tester, if you do so it's because you know how to handle regex, if you have no idea of how to do that, ask it too.
更多推荐
发布评论