Reputation: 1806
I have a variable temp
:
String temp = "Ms Abc`<[email protected]`>;Mr Cde`<[email protected]`>;Miss Xyz`<[email protected]`>";
Now I have to split this variable temp
string into an ArrayList
or String[]
so that I can extract title
, name
, emailid
for insertion into a database. I'm only able to split the email id using following code:
ArrayList emailIdList = new ArrayList();
Pattern p = Pattern.compile("\\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}\\b",Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(s);
while (m.find()){
emailIdList.add(m.group());
}
But I'm having a problem getting the title and name as I am stuck with the logic.
How this can be done?
Upvotes: 0
Views: 3167
Reputation: 272
I would suggest to use split multiple times and store value in collection like ArrayList.
String temp = "Ms Abc`<[email protected]`>;Mr Cde`<[email protected]`>;Miss Xyz`<[email protected]`>";
/* Initializing arralists */
ArrayList<String> title = new ArrayList<String>();
ArrayList<String> name = new ArrayList<String>();
ArrayList<String> email = new ArrayList<String>();
/* Splitting each record */
String [] eachRecord = temp.split(";");
for (int i = 0; i < eachRecord.length; i++) {
/* Fetch value in each record */
String [] intermediateValue = eachRecord[i].split(" ");
title.add(intermediateValue[0]);
intermediateValue = intermediateValue[1].split("`<");
name.add(intermediateValue[0]);
intermediateValue = intermediateValue[1].split("`>");
email.add(intermediateValue[0]);
}
But with this method you need to make sure that values will come in same format. Any change in format will result in failure of code or exception in your application. I hope this helps.
Upvotes: 1
Reputation: 77064
Split first on the ;
to separate each entry:
String[] entry = temp.split(";");
For your example entry
will contain:
[0] => "Ms Abc`" [1] => "Mr Cde`" [2] => "Miss Xyz`"
For a single entry, now we want to extract the salutation (I think you're calling this title
), name, and email address. You can use a simple regular expression to do that:
Pattern p = Pattern.compile("(\\w+)\\s(\\w+)`<(.+)`>");
Then just iterate over entry
and read the groups from the regular expression:
// for each of the entries
for(String e : entry){
Matcher m = p.matcher(e);
if(m.find()){
String title = m.group(1);
String name = m.group(2);
String email = m.group(3);
}
}
Upvotes: 3