我在这里有一个电子邮件模式
Pattern pattern = Pattern.compile("^[A-Za-z0-9+_.-]+@(.+)$");
我也有一个字符串包含消息
String message = "Han [email protected] im 20 years old, i just came here to say nothing..";
我的问题是将模式匹配到字符串时我什么也没得到。我在这里做什么
Pattern pattern = Pattern.compile(pattern);
Matcher m = pattern.matcher(message);
if(m.find()) {
Log.d("TAG", m.group(1));
}else {
Log.d("TAG", "No email found on string");
}
如果我的代码正确,我不知道,但是我只是简单地跟随一些文章使用正则表达式来获取字符串中的单词。
您需要从正则表达式中删除锚点。
Pattern pattern = Pattern.compile("\\b[A-Za-z0-9+_.-]+@(?:[^.\\s]+\\.)+\\w{2,4}\\b");
例子:
String message = "Han [email protected] im 20 years old, i just came here to say nothing..";
Pattern pattern = Pattern.compile("\\b[A-Za-z0-9+_.-]+@(?:[^.\\s]+\\.)+\\w{2,4}\\b");
Matcher m = pattern.matcher(message);
if(m.find())
{
System.out.println("TAG " + m.group());
}
else {
System.out.println("TAG " + "No email found on string");
}
输出:
TAG [email protected]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句