By using our mini forum, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy

Q: Extract Emails in Java

+7 votes

Write a program to extract all email addresses from given text. The text comes at the first input line. Print the emails in the output, each at a separate line. Emails are considered to be in format <user>@<host>, where:

  • <user> is a sequence of letters and digits, where '.', '-' and '_' can appear between them. Examples of valid users: "stephan", "mike03", "s.johnson", "st_steward", "softuni-bulgaria", "12345". Examples of invalid users: ''--123", ".....", "nakov_-", "_steve", ".info".
  • <host> is a sequence of at least two words, separated by dots '.'. Each word is sequence of letters and can have hyphens '-' between the letters. Examples of hosts: "", "", "", "". Examples of invalid hosts: "helloworld", ".unknown.soft.", "invalid-host-", "invalid-".
  • Example of valid emails:,,,,


how to extract emails in java

asked in Java category by user eiorgert
edited by user golearnweb

1 Answer

+1 vote
Best answer

You can use regular expressions - REGEX to find the e-mails + Pattern and Matcher

Read more about them HERE:

Here's my solution:

import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Pr_01_ExtractEmails {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(;
        String input = scanner.nextLine();

        Pattern pattern = Pattern.compile("([a-z0-9_.-]+)@([a-z0-9_.-]+[a-z])");
        Matcher matcher = pattern.matcher(input);

answered by user hues
edited by user golearnweb