用于在Java中读取CSV的正则表达式[重复](Regular Expression for reading CSV in Java [duplicate])

编程入门 行业动态 更新时间:2024-10-10 19:26:12
用于在Java中读取CSV的正则表达式[重复](Regular Expression for reading CSV in Java [duplicate])

可能重复: 在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 lmno

I 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.

更多推荐

本文发布于:2023-08-04 18:27:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1419243.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:正则表达式   CSV   Java   Regular   duplicate

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!