简体   繁体   English

在Java中使用分隔符分割字符串

[英]Split String using delimiter in Java

I need help in splitting two email address which are seperated by a Delimiter 'AND'. 我需要拆分两个以分隔符“ AND”分​​隔的电子邮件地址时需要帮助。 I have issue when splitting, when the email address has got the characters'AND' in the email id. 拆分时,当电子邮件地址的电子邮件ID中包含字符“ AND”时,我遇到了问题。 For eg, if the email address that needs to be split is something like the below. 例如,如果需要拆分的电子邮件地址如下所示。 There are no whitespaces between the two email address. 两个电子邮件地址之间没有空格。

'anandc@AND.comANDxyz@yahoo.co.in', and the delimiter is'AND' 

In the above case, there seems to be three items extracted instead of two. 在上述情况下,似乎提取了三个项目,而不是两个。 Can someone please help me solve this. 有人可以帮我解决这个问题吗? Thanks in Advance 提前致谢

You can use " AND " as delimiter. 您可以使用" AND "作为分隔符。

 String str="anandc@AND.com AND xyz@yahoo.co.in";
 String[] emailArr=str.split(" AND "); 

Or you can use following regex 或者您可以使用以下regex

  String str = "anandc@AND.com AND xyz@yahoo.co.in";
  Pattern p = Pattern.compile("[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+
                                   (\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})");
  Matcher matcher = p.matcher(str);
  while (matcher.find()) {
     System.out.println(matcher.group(0));
  }

Out put 放出

 anandc@AND.com
 xyz@yahoo.co.in

Giving correct output 提供正确的输出

public class Test {
        public static void main(String args[]) {
            String text = "anandc@AND.com AND xyz@yahoo.co.in ";
            String[] splits = text.split(" AND ");
            for (int i = 0; i < splits.length; i++) {
                System.out.println("data :" + splits[i]);
            }
        }

    }

Output is 输出是

data :anandc@AND.com    
data :xyz@yahoo.co.in 

用这个 :

String[] splits = text.split("\\\\s+AND\\\\s+");

http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String) the regular expression will be case sensitive http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split(java.lang.String)正则表达式区分大小写

actually, the best is to use delimiters exression that you are sure will not be in the adress 实际上,最好是使用定界符扩展名,以确保不会出现在地址中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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