Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
191 views
in Technique[技术] by (71.8m points)

Parsing CSV input with a RegEx in java

I know, now I have two problems. But I'm having fun!

I started with this advice not to try and split, but instead to match on what is an acceptable field, and expanded from there to this expression.

final Pattern pattern = Pattern.compile(""([^"]*)"|(?<=,|^)([^,]*)(?=,|$)");

The expression looks like this without the annoying escaped quotes:

"([^"]*)"|(?<=,|^)([^,]*)(?=,|$)

This is working well for me - either it matches on "two quotes and whatever is between them", or "something between the start of the line or a comma and the end of the line or a comma". Iterating through the matches gets me all the fields, even if they are empty. For instance,

the quick, "brown, fox jumps", over, "the",,"lazy dog"

breaks down into

the quick
"brown, fox jumps"
over
"the"

"lazy dog"

Great! Now I want to drop the quotes, so I added the lookahead and lookbehind non-capturing groups like I was doing for the commas.

final Pattern pattern = Pattern.compile("(?<=")([^"]*)(?=")|(?<=,|^)([^,]*)(?=,|$)");

again the expression is:

(?<=")([^"]*)(?=")|(?<=,|^)([^,]*)(?=,|$)

Instead of the desired result

the quick
brown, fox jumps
over
the

lazy dog

now I get this breakdown:

the quick
"brown
 fox jumps"
,over,
"the"
,,
"lazy dog"

What am I missing?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Operator precedence. Basically there is none. It's all left to right. So the or (|) is applying to the closing quote lookahead and the comma lookahead

Try:

(?:(?<=")([^"]*)(?="))|(?<=,|^)([^,]*)(?=,|$)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...