Question

I'm trying to read a structure of a text file in a certain way. The text file is kind of a user-friendly configuration file.

Current structure of file (structure can be changed if necessary):

info1=exampleinfo
info2=exampleinfo2
info3="example","example2","example3"
info4="example","example2","example3"

There is no real difficulty in getting the first two lines, but the latter two are more difficult. I need to put both in two seperate string arrays that I can use. I could use a split string, but the problem is in that in the info4 array, the values can contain comma's (this is all user input).

How to go about solving this?

Was it helpful?

Solution

The reason you're having trouble writing parser is that you're not starting with a good definition of the file format. Instead of asking how you should parse it if there are commas, you should be deciding how to properly encode values with commas. Then parsing is simple.

If this file is written by non-technical users who can't be trusted with a complex format (like json), consider a format like:

info1=exampleinfo
info2=exampleinfo2
info3=example
    example2
    example3
info4=example
    example2
    example3

That is, don't mess around with quotes and commas. Users understand line breaks and spaces pretty well.

OTHER TIPS

I'm 100% in favor of @DavidHeffernan's solutions, JSON would be great. And @ScottMermelstein's solution of a program that builds the output - that's probably your best bet if possible, not allowing the user to make a mistake even if they wanted to.

However, if you need them to build the textfile, and you're working with users who can't be trusted to put together valid JSON, since it is a picky format, maybe try a delimiter that won't be used by the user, to separate values.

For example, pipes are always good, since practically nobody uses them:

info1=exampleinfo
info2=exampleinfo2
info3=example|example2|example3
info4=example|exam,ple2|example3

All you'd need is a rule that says their data cannot contain pipes. More than likely, the users would be ok with that.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top