How to get a list of multiple emails from a string by using split in Java? -
i'm facing issue hours :( . have string contains bunch of emails in it:
" email1@gmail.com , 'email2@gmail.com,email3@gmail.com, email4@gmail.com' , 'email5@gmail.com ,email6@gmail.com' "
so i'm trying extract each email each substring , end array contains email:
example:
string[] myarray = {email1@gmail.com , email2@gmail.com, email3@gmail.com, email4@gmail.com, email5@gmail.com};
here's code:
string str = "email1@gmail.com , 'email2@gmail.com,email3@gmail.com, email4@gmail.com' , 'email5@gmail.com ,email6@gmail.com'"; string[] newarray = str.split(","); for(int = 0 ; < newarray.length; i++) { if(newarray[i].contains(",")) { newarray = newarray[i].split(","); } }
keep in mind substring may have multiple emails in it. thank help!
you can use pattern matching , regex, simple email follows : \w+@\w+.com
: multiplewordcharacter@multiplewordcharacter.com
public static void main(string[] args) { string str = "email1@gmail.com,'email2@gmail.com,email3@gmail.com, email4@gmail.com'" + ", 'email5@gmail.com ,email6@gmail.com'"; matcher m = pattern.compile("\\w+@\\w+.com").matcher(str); list<string> emailslist = new arraylist<>(); while (m.find()){ emailslist.add(m.group()); } string[]emailsarray = emailslist.toarray(new string[0]); // if need array system.out.println(arrays.tostring(emailsarray)); }
i used list @ first because it's easy add element dunamiclly, can't array, @ the, end still can use array code wrote
and print :
[email1@gmail.com, email2@gmail.com, email3@gmail.com, email4@gmail.com, email5@gmail.com, email6@gmail.com]
Comments
Post a Comment