0

I am parsing a csv file with Apache Commons CSVRecord and CSVFormat in Java I got the following record in String format Records : CSVRecord [comment=null, mapping={Id=0, FirstName=1, LastName=2}, recordNumber=1, values=[1, John, Wayne]]

I need to extract the values only For ex: 1, John, Wayne

Used the following options to get the result.

String[] split = record.split("values=\\[");
String result = split[1].substring(0, split[1].length() - 2);

My Question is: Is there a better option(Faster) than this in Java?

8
  • Could you please paste an example of your input csv file? Commented May 29, 2019 at 15:31
  • Are you trying to parse CSVRecord.toString() value? What exactly are you doing? Commented May 29, 2019 at 15:31
  • What Karol said. Use one of the CSVRecord.get() methods or the CSVRecord.iterator() or CSVRecord.toMap() to acces the values Commented May 29, 2019 at 15:33
  • Yes. I am trying to parse the CSVRecord.toString() value Commented May 29, 2019 at 15:33
  • 1
    Trying to parse from the string representation has pitfalls in addition to being less performant. For instance @Guilherme's solution will fail if one of the values contains values=[ or , (the first one is unlikely, the second maybe less) Commented May 29, 2019 at 15:57

1 Answer 1

1

Try this:

String txt = "CSVRecord [comment=null, mapping={Id=0, FirstName=1, LastName=2}, recordNumber=1, values=[1, John, Wayne]]";

String[] sub = txt.substring(txt.indexOf("values=[")).split("[\\[\\]]");


System.out.println(sub[1]);
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.