如何从matcher.group()获取字符串并将其存储在Java中的单独字符串变量中?

时间:2019-07-13 19:50:17

标签: java

String emailAdress = "yourname@yourdomin.com";
Pattern emailAddress = Pattern.compile("(.*)(@)(.*)");
Matcher matchEmailAddress = emailAddress.matcher(emailAdress);
String secondPartOfEmail;
while(matchEmailAddress.find()){
    System.out.println(matchEmailAddress.group(1));
    System.out.println(matchEmailAddress.group(3));
}

当我运行此源代码时,输​​出为:

  

您的姓名
yourdomin.com

我想将 yourdomain.com 存储在字符串类型变量中,以便以后使用。我的意思是matchEmailAddress匹配器中的group(3)。

我已经尝试过:

String secondPartOfEmail = matchEmailAddress.group(3)

但发生错误。

1 个答案:

答案 0 :(得分:0)

假设您只想匹配一个电子邮件地址,则可以执行以下操作:

String emailAdress = "yourname@yourdomin.com";
Pattern emailAddress = Pattern.compile("(.*)(@)(.*)");
Matcher matchEmailAddress = emailAddress.matcher(emailAdress);

matchEmailAddress.find(); //find the next substring matching your pattern
String secondPartOfEmail = matchEmailAddress.group(3);