1

I need to read a file with this format:

(w,x,y,z),(w,x,y,z), ... ,(w,x,y,z);

All on one line.

//edit:

I eventually will need to do this on files like the following as well:

(w,x,y,z_1 ... z_n),(w,x,y,z_1 ... z_n), ... ,(w,x,y,z_1 ... z_n);

so simply reading past 3 commas is not going to cut it.

My plan is to read the whole file into a String using the Scanner class, then splitting it up in an array of (w,x,y,z) parts and then splitting that up into the actual w, x, y and z. Eventually the data in the file would end up in a list of objects something like:

public class DataBean {
    private String w, x, y, z;
    ...
}

I'm having trouble coming up with a regular expression for this though. I tried

String[] allSystems = scanner.nextLine ( ).split ( "),(" );

and sure, it cuts the string up, but I feel it's not the most elegant solution. If anyone has a better idea I'd love to hear!

1
  • 2
    Frankly I don't think you're going to find a more elegant solution than that. Elegant != Fancy. String[] allSystems = scanner.nextLine ( ).split ( "),(" ); is a very clean way to do it Commented Oct 17, 2013 at 19:27

2 Answers 2

3

You can try:

String[] allSystems = scanner.nextLine ( ).split ( "(?<=\\)),(?<!\\()" );

You get (w,x,y,z), (w,x,y,z), (w,x,y,z);

Next, for get w, x, y, z, you can do:

String system = "(w,x,y,z);";

String[] data = system.replaceAll("\\(|\\);?", "").split(",");
Sign up to request clarification or add additional context in comments.

Comments

1

If you use line.split("(^\\(|\\),\\(|\\);|,)") then you will get a String array with each w, x, y, and z as its own element in the array. The first item in the array will be an empty String, but if you start at index 1 you can easily use this to construct your DataBean objects:

String[] data = line.split("(^\\(|\\),\\(|\\);|,)");

List<DataBean> dataBeans = new ArrayList<DataBean>();
for (int i = 1; i < data.length; i += 4) {
    dataBeans.add(new DataBean(data[i], data[i+1], data[i+2], data[i+3]);
}

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.