Advertisement
dimipan80

Java Regex: Extract Emails

Aug 2nd, 2017
658
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.99 KB | None | 0 0
  1. /* Write a program to extract all email addresses from given text.
  2.  * The text comes at the first input line.
  3.  * Print the emails in the output, each at a separate line.
  4.  * Emails are considered to be in format <user>@<host>, where:
  5.  * <user> is a sequence of letters and digits, where '.', '-' and '_' can appear between them.
  6.  * Examples of valid users: "stephan", "mike03", "s.johnson", "st_steward", "softuni-bulgaria",
  7.  * "12345". Examples of invalid users: ''--123", ".....", "nakov_-", "_steve", ".info".
  8.  * <host> is a sequence of at least two words, separated by dots '.'.
  9.  * Each word is sequence of letters and can have hyphens '-' between the letters.
  10.  * Examples of hosts: "softuni.bg", "software-university.com", "intoprogramming.info",
  11.  * "mail.softuni.org". Examples of invalid hosts: "helloworld", ".unknown.soft.",
  12.  * "invalid-host-", "invalid-".
  13.  * Example of valid emails: info@softuni-bulgaria.org, kiki@hotmail.co.uk,
  14.  * no-reply@github.com, s.peterson@mail.uu.net, info-bg@software-university.software.academy. */
  15.  
  16.  
  17. import java.io.BufferedReader;
  18. import java.io.IOException;
  19. import java.io.InputStreamReader;
  20. import java.util.regex.Matcher;
  21. import java.util.regex.Pattern;
  22.  
  23. public class ExtractEmails {
  24.     public static void main(String[] args) {
  25.         StringBuilder text = new StringBuilder();
  26.  
  27.         try (BufferedReader reader =
  28.                      new BufferedReader(new InputStreamReader(System.in))) {
  29.  
  30.             String line = reader.readLine();
  31.             while (!line.equals("end")) {
  32.                 text.append(line);
  33.  
  34.                 line = reader.readLine();
  35.             }
  36.  
  37.         } catch (IOException e) {
  38.             e.printStackTrace();
  39.         }
  40.  
  41.         Pattern pattern = Pattern
  42.                 .compile("(^|\\s)[a-z0-9][-._a-z0-9]*[a-z0-9]@[a-z0-9][-.a-z0-9]*[a-z0-9]\\.[a-z]{2,}");
  43.  
  44.         Matcher matcher = pattern.matcher(text);
  45.         while (matcher.find()) {
  46.             System.out.println(matcher.group().trim());
  47.         }
  48.     }
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement