2

我想执行以下功能:

从给定的段落中提取给定的字符串,例如

String str= "Hello this is paragraph , Ali@yahoo.com . i am entering  random  email here as this one  AHmar@gmail.com " ; 

我要做的是解析整个段落,阅读电子邮件地址,并打印他们的服务器名称,我已经尝试过使用for 循环substring 方法,确实使用 过indexOf,但可能是我的逻辑不太好,有人可以请帮帮我?

4

3 回答 3

3

对于这种情况,您需要使用正则表达式。

试试下面的正则表达式: -

String str= "Hello this is paragraph , Ali@yahoo.com . i am " +
            "entering  random  email here as this one  AHmar@gmail.com " ;

Pattern pattern = Pattern.compile("@(\\S+)\\.\\w+");
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
     System.out.println(matcher.group(1));
}

输出: -

yahoo
gmail

更新: -

这是带有substring和的代码indexOf:-

   String str= "Hello this is paragraph , Ali@yahoo.com . i am " +
        "entering  random  email here as this one  AHmar@gmail.com " ;

   while (str.contains("@") && str.contains(".")) {

        int index1 = str.lastIndexOf("@");  // Get last index of `@`
        int index2 = str.indexOf(".", index1); // Get index of first `.` after @

        // Substring from index of @ to index of .      
        String serverName = str.substring(index1 + 1, index2);
        System.out.println(serverName);

        // Replace string by removing till the last @, 
        // so as not to consider it next time
        str = str.substring(0, index1);

    } 
于 2012-10-23T20:30:46.387 回答
2

您需要使用正则表达式来提取电子邮件。从这个测试工具代码开始。接下来,构建您的正则表达式,您应该能够提取电子邮件地址。

于 2012-10-23T20:29:39.117 回答
1

试试这个:-

  String e= "Hello this is paragraph , Ali@yahoo.com . i am entering random email here as this one AHmar@gmail.comm";
  e= e.trim();  
  String[] parts = e.split("\\s+");  
  for (String e: parts) 
  {
  if(e.indexOf('@') != -1)
  {
   String temp = e.substring(e.indexOf("@") + 1); 
  String serverName = temp.substring(0, temp.indexOf(".")); 
  System.out.println(serverName);        }}
于 2012-10-23T20:31:11.203 回答