【问题标题】:take a part of a string in java在java中获取字符串的一部分
【发布时间】:2015-05-26 19:02:33
【问题描述】:

我有一个字符串,其中包含 4 个属性,它们之间有 3 个空格(姓名、姓氏、电子邮件、电话)。例如:

"Mike   Tyson   mike@hotmail.com   0 999 999 99 99"

我需要从这个字符串中获取电子邮件。我搜索了正则表达式和令牌,但找不到任何东西。谢谢。

【问题讨论】:

  • 这解决了问题,谢谢
  • 请发布您尝试过但对您不起作用的正则表达式和代码。
  • 是的,如果它是一种刚性形式,就像@Pshemo 所说的那样,分成 3 个空格。

标签: java regex string token


【解决方案1】:
  1. split 您的字符串使用 3 个空格来获取令牌数组
  2. 获取你感兴趣的token(这里将被索引为[2]

【讨论】:

    【解决方案2】:

    您可以使用以下内容并提取组 1:

    ^[^\\s]+\\s+[^\\s]+\\s+([^\\s]+)
    

    代码:

    String str = "Mike   Tyson   mike@hotmail.com   0 999 999 99 99";
    Matcher matcher = Pattern.compile("^[^\\s]+\\s+[^\\s]+\\s+([^\\s]+)").matcher(str);
    
    while (matcher.find()) {
       System.out.println(matcher.group(1));
    }
    

    【讨论】:

      【解决方案3】:
      String string = "Mike   Tyson   mike@hotmail.com   0 999 999 99 99";
      System.out.println(string.split("   ")[2]); // your email
      

      这很简单。使用方法split 获取字符串数组并调用需要的元素进行索引。

      【讨论】:

        【解决方案4】:

        一个班轮...

        String s = "Mike   Tyson   mike@hotmail.com   0 999 999 99 99";
        String email = s.trim().split(" ")[2];
        

        【讨论】:

          【解决方案5】:

          使用下面的代码sn -p -

          import java.util.regex.Matcher;
          import java.util.regex.Pattern;
          
          public class ExtractMail{
          
              public static void main(String[] args){
          
                  String str = "Mike   Tyson   mike@hotmail.com   0 999 999 99 99";
                  Matcher matcher = Pattern.compile("[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+").matcher(str);
          
                  while (matcher.find()) {
                     System.out.println(matcher.group());
                  }
          
              }
          
          }
          

          【讨论】:

            【解决方案6】:

            按照 OP 的要求,这里有一个带有正则表达式的版本:

            public static void test()
            {
                String str = "Mike   Tyson   mike@hotmail.com   0 999 999 99 99";
                Matcher matcher = Pattern.compile("[^ ]*@[^ ]*").matcher(str);
            
                while (matcher.find()) {
                   System.out.println(matcher.group(0));
                }
            }
            

            [^ ]*@[^ ]* 匹配@ 字符周围的任何字符(空格除外)。

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2015-02-02
              • 2013-04-18
              • 2016-06-13
              • 2011-07-02
              • 1970-01-01
              相关资源
              最近更新 更多