cuzyoo
cuzyoo

Reputation: 67

Find E-Mail Adresses in a text

Can somebody tell me how to find E-Mail Adresses in a text?

Example text:

"Hey,

I just blahblah

E-Mail: [email protected]

Another would be [email protected]"

So the output is:

[email protected]
[email protected]

I tried Regex, but I got no idea how I can do this over an entire text...

Pattern pattern = Pattern.compile("[A-Z0-9._%+-]+@[A-Z0-9.-]+\\.[A-Z]{2,4}");
Matcher matcher = pattern.matcher("[email protected]".toUpperCase());

if(matcher.matches()){
    System.out.println("Mail found!");
}else{
    System.out.println("No Mail...");
}

Can somebody help me? :(

Greetings!

Upvotes: 0

Views: 67

Answers (2)

Runcorn
Runcorn

Reputation: 5224

I am not sure about the regex expression you have provided. But if it is good and serves your purpose then you can use following to extract the string,

Matcher matcher = pattern.matcher("[email protected]".toUpperCase());
String result;
while (matcher.find()) { 
    // result now will contain  the email address
    result = matcher .group();
    System.out.println(result);
}

Upvotes: 0

hwnd
hwnd

Reputation: 70722

They're so many different types of email address formats that it is hard to match all of them. A simple (for your structured data) but no so effective approach would be the following:

String s  = "Hey,\n" +
            "I just blahblah\n" +
            "E-Mail: [email protected]\n" +
            "Another would be [email protected]";

Pattern p = Pattern.compile("\\S+@\\S+");
Matcher m = p.matcher(s);

while (m.find()) {
  System.out.println(m.group());
}

Output

[email protected]
[email protected]

Upvotes: 3

Related Questions