简体   繁体   中英

String.split() doesn't work with my regex that searches for comma-separated items

Could you please tell why my regex pattern which works in String.matches() doesn't split given string using String.split ?

Here is the code:

String text = "sdf.an@dfgdfg.com;   sdfsdf@fdfd.erff";
String regex = "(\\b[\\w.%-]+@[\\w.]+\.[a-zA-Z]{2,4}\\b)([,;]\\s*\\b[\\w.%-]+@[\\w.]+\.[a-zA-Z]{2,4}\\b)*";
String [] emails = text.split(regex);

emails is empty :(

I believe that String.split needs a delimiter not the whole pattern.

In your case you can simply put this

text.split(";\\s*")

Why don't you simply use the regex ";\\\\s*" ?

String text = "sdf.an@dfgdfg.com;   sdfsdf@fdfd.erff";
String regex = ";\\s*";
String [] emails = text.split(regex);
for(String ss : emails) System.out.println(ss);

OUTPUT:

sdf.an@dfgdfg.com
sdfsdf@fdfd.erff

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM