I am working on a project for a beginners java course, I need to read a file and turn each line into an object, which i will eventually print out as a job listing. (please no ArrayList suggestions) so far i have gotten that file saved into a String[], which contains strings like this:
*"iOS/Android Mobile App Developer - Java, Swift","Freshop, Inc.","$88,000 - $103,000 a year"
"Security Engineer - Offensive Security","Indeed","$104,000 - $130,000 a year"
"Front End Developer - CSS/HTML/Vue","HiddenLevers","$80,000 - $130,000 a year"*
what im having trouble with is trying to split each string into its three parts so it can be inputted into my JobService createJob method which is as shown:
public Job createJob(String[] Arrs) {
Job job = new Job();
job.setTitle(Arrs[0]);
job.setCompany(Arrs[1]);
job.setCompensation(Arrs[2]);
return job;
}
I am terrible at regex but know that trying to .split(",") will break up the salary portion as well. if anyone could help figure out a reliable way to split these strings to fit into my method i would be grateful!!! Also im super new, please use language the commoners like me will understand...
CodePudding user response:
You need a slightly better split criteria, something like \","
for example...
String text = "\"iOS/Android Mobile App Developer - Java, Swift\",\"Freshop, Inc.\",\"$88,000 - $103,000 a year\"";
String[] parts = text.split("\",");
for (String part : parts) {
System.out.println(part);
}
Which prints...
"iOS/Android Mobile App Developer - Java, Swift
"Freshop, Inc.
"$88,000 - $103,000 a year"
Now, if you want to remove the quotes, you can do something like....
String text = "\"iOS/Android Mobile App Developer - Java, Swift\",\"Freshop, Inc.\",\"$88,000 - $103,000 a year\"";
String[] parts = text.split("\",");
for (String part : parts) {
System.out.println(part.replace("\"", ""));
}
Regular Expression
No, I'm not that good at it either. I tried...
String[] parts = text.split("^\"|\",\"|\"$");
And while this works, it produces 4 elements, not 3 (first match is blank).
You could remove the first and trailing quotes and then just use ","
instead...
text = text.substring(1, text.length() - 2);
String[] parts = text.split("\",\"");
CodePudding user response:
- trim leading and trailing quotes
- split on
","
As code:
String[] columns = line.replaceAll("^\"|\"$", "").split("\",\"");
^"|"$
means "a quote at start or a quote at end"
The regex for the split is just a literal ","