0

I have here a pattern for email

Pattern pattern = Pattern.compile("^[A-Za-z0-9+_.-]+@(.+)$");

also i have a String contains messages

String message = "Han hannibal@domain.com im 20 years old, i just came here to say nothing..";

my problem is when matching pattern to string i get nothing. here what i do

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");
}

i don't if my code was right but i just simply follow some article on fetching words on string using regex.

Hannibal Burr
  • 49
  • 1
  • 7
  • since its for android,why not use android inbuilt email address validation. android.util.Patterns.EMAIL_ADDRESS.matcher(input string).matches(); – Aniruddha K.M Mar 09 '15 at 07:52

1 Answers1

0

You need to remove the anchors from your regex.

Pattern pattern = Pattern.compile("\\b[A-Za-z0-9+_.-]+@(?:[^.\\s]+\\.)+\\w{2,4}\\b");

Example:

String message = "Han hannibal@domain.com 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");
}

Output:

TAG hannibal@domain.com
Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
  • by the way, i forgot is this work also on android? coz android is java base right? – Hannibal Burr Mar 09 '15 at 04:02
  • @AvinashRaj can we continue on chat? if have time. :) i got i more thing to ask :) hahaha – Hannibal Burr Mar 09 '15 at 04:38
  • Allowing only 2-4 characters for TLD is simply behind the time. There are many new generic TLD with more than 4 characters. Heck, there are even internationalized TLD. – nhahtdh Mar 09 '15 at 05:28
  • yep, this would work for simpler case. For complex cases, he may consider reading [this](http://stackoverflow.com/questions/201323/using-a-regular-expression-to-validate-an-email-address) – Avinash Raj Mar 09 '15 at 05:32