2

I need to split a CSV file (which I read in as String) containing orders. Parsing rules of this CSV are not that complex:

Each order has several lines (no fix number)

Each order begins with one line (initiator):

111;222;dynamic content

Each order ends with two lines (terminator):

111;333;dynamic content
111;333;dynamic content

Initiator and terminator have to be included in the outcome of the split.

[EDIT] I do not need to use regexp. This was just my first idea. I could also use another solution, if it is easier. [/EDIT]

I have not much experience with regexp, so even getting started takes a long time :-( E.g., I tried the following:

String[] parts = body.split("111;333;.*111;333;");

Expected result: Splitter is 111;333; to 111;333; - remember, every order ends with two lines, both begin with 111;333; so, String[] should contain the correct number of orders IMO. However, there is only one String in the array which contains everything.

I played around with some other regexps, but I cannot get a good result. Can some one help me and tell me the regular expression for this split? Thanks...

Best regards, Kai

7
  • Do you must use regex for this? Why not a simple straight String.split() by lines then by field separator? Here for an example. Commented Dec 9, 2013 at 11:15
  • Not sure you wanna do that with a regular expression. It is gonna be hairy and very hard to maintain. Parse lines using a tokenizer instead. Commented Dec 9, 2013 at 11:15
  • 1
    I do not have to use regexp! This was just my first idea. An easier solution would be appreciated, of course! Commented Dec 9, 2013 at 11:18
  • CSV is the acronym for Comma-Separated Values (or Character-Separated Values) that means that each column of your file is separate by a ';' or another character. You can simply split you row's string using that character and get your data. Commented Dec 9, 2013 at 11:22
  • @KaiWähner link I posted in my first comment for an example using String.split() Commented Dec 9, 2013 at 11:23

1 Answer 1

4

I really would discourage you to try this task using regex. There are many Java libraries for doing this for you. These libraries are tested and very well known. Just take any of them. You will save time and effort. I have good experience using opencsv.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.