Reputation: 1447
An example of my original data format:
196 242X 3
186 B302 3
22 BO377 1
To extract data, I split along the delimiter (\t
):
EventDAO dao = new SimpleFileRatingDAO(inputFile, "\t");
However, my data format changed, to something like this:
"196";"242X";"3"
"186";"B302";"3"
"22";"BO377";"1"
Is there a regex I can use to extract the data, in a similar way to my previous method?
Upvotes: 0
Views: 1499
Reputation: 11
try it with simple String-manipulations like split and replace:
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
public class Example {
class DataBean{
private String info1;
private String info2;
private String info3;
public DataBean(String info1, String info2, String info3){
this.info1 = info1;
this.info2 = info2;
this.info3 = info3;
}
public String getInfo1() {return info1;}
public void setInfo1(String info1) {this.info1 = info1;}
public String getInfo2() {return info2;}
public void setInfo2(String info2) {this.info2 = info2;}
public String getInfo3() {return info3; }
public void setInfo3(String info3) {this.info3 = info3;}
}
/**
* @param args
* @throws IOException
*
* TODO: do better exc-handling
*/
public static void main(String[] args) throws IOException {
/*
* data.txt:
*
* "196";"242X";"3"
* "186";"B302";"3"
* "22";"BO377";"1"
*/
File dataFile = new File("data.txt");
FileInputStream fis = new FileInputStream(dataFile);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
String strLine;
List<DataBean> data = new ArrayList<DataBean>();
while ((strLine = br.readLine()) != null) {
String[] rawData = strLine.replace("\"", "").split(";");
DataBean dataBean = new Example().new DataBean(rawData[0], rawData[1], rawData[2]);
data.add(dataBean);
}
for (DataBean dataBean : data) {
System.out.println(dataBean.getInfo1() + "-" + dataBean.getInfo2() + "-" + dataBean.getInfo3());
}
br.close();
}
Upvotes: 1
Reputation: 883
Your new reg Exp should be something which match both separators (if they do not apear in data)
"[\t|;]"
SimpleFileRatingDAO seems to allow regular expression: it use the object class which call String.split(str) :
enter code hereEventDAO dao = new SimpleFileRatingDAO(inputFile, "[\t|;]");
leads to:
myLine.split("[\t|;]")
If your data may contains those separators characters but only between quotation marks: you need to split on the comma only if that comma has zero, or an even number of quotes ahead of it:
"[\t|;](?=([^\"]*\"[^\"]*\")*[^\"]*$)"
Thanks to Bart Kiers who inspire me.
Upvotes: 2