java

How to extract email addresses from a string in Java

In this tutorial, we are going to see how to extract email addresses from a string in Java. Regular Expressions or Regex is an API for defining patterns that can be used to find, manipulate, and edit a string in Java. Email validation is an example where we can apply Regex. Regex is widely used to define constraints. Regular expressions are provided under java.util.regex package.
 

Java Program to extract email addresses from a string:

For example, if we want to extract the email address [email protected] and [email protected] from the string “blah blah <[email protected]> && mail: [email protected]”, we can use the following code :
 

 

import java.util.regex.*;

public class Main
{
    public static void main(String[]args) 
    {
      String s = "bla bla <[email protected]> && mail:[email protected]";
      Matcher m = Pattern.compile("[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+").matcher(s);
      
      while (m.find()) 
      {
          System.out.println(m.group());
      }
    }
}

Output:

[email protected]
[email protected]
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *