想要从匹配特定模式的字符串返回提取的值。 例如:我想从String s =“abc@hotmail.com”
中提取“hotmail”import java.util.*;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
class regexprac{
public static void main(String args[]){
String x = "xyz@hotmail.com";
String existingdomain = "hotmail";
Pattern emailPattern = Pattern.compile("^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"+ "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$");
if(existingdomain.equals(emailPattern.matcher(x))){
System.out.println("Found it");
}else{
System.out.println("Not found it");
}
}
}
答案 0 :(得分:0)
if(existingdomain.equals(emailPattern.matcher(x))){
您正在将Matcher
对象与字符串进行比较。这永远不会评估为真。请参阅Pattern.matcher()
。
您需要在匹配器上调用find()
和group()
方法,并将返回值与字符串进行比较。
<强>更新强>
String x = "xyz@hotmail.com";
String y = "xyz@outlook.com";
Pattern p = Pattern.compile(".+@([^.]+)\\.");
Matcher m = p.matcher(x);
if (m.find()) {
System.out.println("found: " + m.group(1));
}
m = p.matcher(y);
if (m.find()) {
System.out.println("found: " + m.group(1));
}
输出:
found: hotmail found: outlook
答案 1 :(得分:0)
试试这个:
import java.util.*;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
class regexprac{
public static void main(String args[]){
String x = "xyz@hotmail.com";
String existingdomain = "hotmail";
Pattern emailPattern = Pattern.compile("(^[A-Z0-9._%+-]+)(@)([A-Z0-9.-]+)(\\.)([A-Z]{2,6}$)", Pattern.CASE_INSENSITIVE);
Matcher matcher = emailPattern.matcher(x);
if(matcher.find())){
System.out.println("Found it");
String provider = matcher.group(2);
}else{
System.out.println("Not found it");
}
}
}