Reputation: 1954
I'm trying to split a string into parts where a ,
()
spaces
are involved.
It's coming from a combo box item. It looks like this
ComboBox Item
(123456) LastName, FirstName MiddleName
And I want to separate it into parts
int employeeNumber = 123456
String lastName = LastName
String firstName = firstName
String middleName = middleName
So I tried this but can't get the result I want because it seems it's only splitting it by commas.
String facultyName = adviserJcbx.getSelectedItem().toString().trim();
String [] facultyNameSplit = facultyName.split(",");
String facultyLastName = facultyNameSplit[0];
String facultyFirstName = facultyNameSplit[1];
//String facultyMiddleName = facultyNameSplit[2];
I get an error if I try something like facultyName.split(",()\\s+");
All these four variables will be used in a CALLABLE
stored proc's WHERE clause like
SELECT id from table WHERE empNo = employeeNumber AND lName = lastName AND fName = firstName AND mName = middleName;
I hope you can help because I researched online but can't find any example where more characters are involved on split.
Also, is there any easier way to get an Id of an element in GUI element without having to create a stored procedure like the ones I'm creating
CALL getFacultId(?,?,?,?);
Here's the screenshot.
My goal is to get the Id of what is selected in combo box by splitting them and supplying it to the getFacultyId(?,?,?,?)
stored procedure.
Thanks in advance.
Upvotes: 1
Views: 41
Reputation: 27966
I would suggest you use a regular expression rather than split:
Pattern facultyPattern = Pattern.compile("\((\\d+)\) (\\w+), (\\w+) (\\w+)");
Matcher facultyMatcher = facultyPattern.match(facultyString);
if (facultyMatcher.matches() {
int id = Integer.parseInt(facultyMatcher.group(1));
String lastName = facultyMatcher.group(2);
String firstName = facultyMatcher.group(3);
String middleName = facultyMatcher.group(4);
...
} else {
// handle mismatch
}
Upvotes: 1
Reputation: 159114
Use a regex like this:
\(([^)]*)\)\s*([^,]+),\s*(\S+)\s*(\S*)
Sample Java code for that:
String input = "(123456) LastName, FirstName MiddleName";
String regex = "\\(([^)]*)\\)\\s*([^,]+),\\s*(\\S+)\\s*(\\S*)";
Matcher m = Pattern.compile(regex).matcher(input);
if (m.matches()) {
System.out.println("empNo = " + m.group(1));
System.out.println("lName = " + m.group(2));
System.out.println("fName = " + m.group(3));
System.out.println("mName = " + m.group(4));
}
Output
empNo = 123456
lName = LastName
fName = FirstName
mName = MiddleName
Upvotes: 3
Reputation: 12378
I think you can CONCAT
these four columns into format you mentioned:
SELECT id
from table
WHERE CONCAT('(', empNo, ') ', lName, ', ', fName, ' ', mName) = ?;
Upvotes: 0