0

I have the following usecase and looking for the right solution.

We are reading a csv file and populating a POJO.One column in from the file could map to multiple fields in the POJO.

eg:

Class Test {

private String field1;
private String field2;
private String field3;
......
other fields
---
getter methods
.....
 setter methods 
}

Let us say value of column XXXX from file is 123_TEST_34_THJ

the field1 value is 123 field2 value is 34 filed3 value THJ

I can do this in the Java code, but I am looking a solution to split this dynamically. Let us say the value of XXXX is now changed to 124_34_THJ, I want my code to work just with a configuration change. What would be a better solution? Please let me know if the question is not clear.

Java Guy
  • 3,391
  • 14
  • 49
  • 55
  • So you want to split `XXXX` at `_` and then filter away `TEST`? – Keppil Jul 11 '12 at 05:26
  • 1
    The question is not clear - what are the possible rules for mapping value to object? – RonK Jul 11 '12 at 05:29
  • 1
    Making something [*too configurable*](http://thedailywtf.com/Articles/The-Enterprise-User-Agent.aspx) can be almost as bad as not configurable enough. Unless this *requires* said flexibility, just write the code (arguably business logic) as part of the actual program. (Keeping in mind the basic rules for separation of concerns and good coding practices.) –  Jul 11 '12 at 05:30
  • Why did you skip `TEST` as a field value? Is that the only term to skip? Was skipping `TEST` an oversight? – Bohemian Jul 11 '12 at 07:11

1 Answers1

1

You could use a regular expression with named captures:

(?<field1>\d+)_\w+_(?<field2>\d+)_(?<field3>\w+)

Then next week it might be...

(?<field2>\d+)_(?<field7>\w+)_(?<field1>\d+)_(?<field3>\w+)

More info on your choices for regex libraries with named captures at Regex Named Groups in Java

Community
  • 1
  • 1
Hounshell
  • 5,321
  • 4
  • 34
  • 51