Skip to content
Related Articles
Open in App
Not now

Related Articles

Extracting all Email Ids in any given String using Regular Expressions

Improve Article
Save Article
  • Last Updated : 04 Mar, 2023
Improve Article
Save Article

Given a string str, the task is to extract all the Email ID’s from the given string.

Example:

Input: “Please send your resumes to Hr@Iwillgetbacktoyou@gmail.com for any business inquiry please mail us at business@enquiry@gmail.com”
Output: Hr@Iwillgetbacktoyou@gmail.com
business@enquiry@gmail.com

Approach: The problem can be solved based on the following idea:

Create a regex pattern to validate the number as written below:   
regex = “^[0-9]{3}[A-Z]{2}[0-9]{8}$

Where,

  • $: Matches the end of the line
  • \s: Matches whitespace
  • \S: Matches any non-whitespace character
  • *: Repeats a character zero or more times
  • \S: Matches any non-whitespace character
  • *?: Repeats a character zero or more times (non-greedy)
  • +: Repeats a character one or more times
  • +?: Repeats a character one or more times (non-greedy)
  • [aeiou]: Matches a single character in the listed set
  • [^ABC]: Matches a single character, not in the listed set
  • [a-z0-9]: The set of characters can include a range
  • (: Indicates where string extraction is to start
  • ): Indicates where string extraction is to end

Follow the below steps to implement the idea:

  • Create a regex expression to extract all the Email Ids from the string.
  • Use Pattern class to compile the regex formed.
  • Use the matcher function to find.

Below is the code implementation of the above-discussed approach:

C++




// C++ code for the above approach
#include <iostream>
#include <regex>
#include <string>
 
using namespace std;
 
void findEmails(string str)
{
    // You can Add n number of Email
    // formats in the below given
    // String Array.
    string strPattern[]
        = { "\\S+@\\S+" };
    for (int i = 0; i < 1; i++) {
        regex pattern(strPattern[i]);
        smatch matches;
        while (regex_search(str, matches, pattern)) {
            cout << matches[0] << endl;
            str = matches.suffix().str();
        }
    }
}
 
int main()
{
    string str = "Please send your resumes on "
                 "Hr@Iwillgetbacktoyou.com "
                 "for any business enquiry please mail us "
                 "on business@enquiry.com "
                 "review-team@geeksforgeeks.org "
                 "and writing.geeksforgeeks.org";
    findEmails(str);
    return 0;
}
 
// This code is contributed by shivamsharma215


Java




// Java code for the above approach
import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
public class GFG {
 
    // Driver Code
    public static void main(String[] args)
    {
 
        // String containing in it
        String str
            = "Please send your resumes on Hr@Iwillgetbacktoyou@gmail.com"
              + "  for any business enquiry please mail us on business@enquiry@gmail.com"
              + " review-team@geeksforgeeks.org "
              + "and writing.geeksforgeeks.org";
 
        findEmails(str);
    }
 
    // Function to extract all email
    // id's from a given string
    static void findEmails(String str)
    {
 
        // You can Add n number of Email
        // formats in the below given
        // String Array.
        String strPattern[] = { "\\S+@\\S+" };
        for (int i = 0; i < strPattern.length; i++) {
            Pattern pattern
                = Pattern.compile(strPattern[i]);
            Matcher matcher = pattern.matcher(str);
            while (matcher.find()) {
                System.out.println(matcher.group());
            }
        }
    }
}


Python3




import re
 
def find_emails(text):
    # List of email patterns to look for
    patterns = [r"\S+@\S+"]
     
    for pattern in patterns:
        # Compile the pattern
        email_regex = re.compile(pattern)
         
        # Find all instances of the pattern in the text
        emails = email_regex.findall(text)
         
        # Print each email found
        for email in emails:
            print(email)
 
# Example usage
text = "Please send your resumes on Hr@Iwillgetbacktoyou@gmail.com" \
       "  for any business enquiry please mail us on business@enquiry@gmail.com" \
       " review-team@geeksforgeeks.org " \
       "and writing.geeksforgeeks.org"
find_emails(text)


C#




// C# code for the above approach
using System;
using System.Text.RegularExpressions;
 
class GFG
{
   
  // Driver Code
  static void Main(string[] args)
  {
 
    // String containing in it
    string str
      = "Please send your resumes on Hr@Iwillgetbacktoyou@gmail.com"
      + "  for any business enquiry please mail us on business@enquiry@gmail.com"
      + " review-team@geeksforgeeks.org "
      + "and writing.geeksforgeeks.org";
 
    findEmails(str);
  }
 
  // Function to extract all email
  // id's from a given string
  static void findEmails(string str)
  {
 
    // You can Add n number of Email
    // formats in the below given
    // String Array.
    string[] strPattern = { @"\S+@\S+" };
    for (int i = 0; i < strPattern.Length; i++) {
      MatchCollection matches
        = Regex.Matches(str, strPattern[i]);
      foreach(Match match in matches)
      {
        Console.WriteLine(match.Value);
      }
    }
  }
}
 
// This code is contributed by ik_9


Javascript




// JS code to implement above approach
 
function findEmails(str) {
    // You can Add n number of Email
    // formats in the below given
    // String Array.
    const strPattern = ["\\S+@\\S+"];
    for (let i = 0; i < 1; i++) {
        const pattern = new RegExp(strPattern[i], 'g');
        let matches;
        while ((matches = pattern.exec(str)) !== null) {
            console.log(matches[0]);
        }
    }
}
 
const str = "Please send your resumes on " +
            "Hr@Iwillgetbacktoyou.com " +
            "for any business enquiry please mail us " +
            "on business@enquiry.com " +
            "review-team@geeksforgeeks.org " +
            "and writing.geeksforgeeks.org";
findEmails(str);
 
//this code is contributed by Tushar_Rokade


Output

Hr@Iwillgetbacktoyou@gmail.com
business@enquiry@gmail.com
review-team@geeksforgeeks.org

Time Complexity: O(n)

Space Complexity: O(n)

Related Articles:


My Personal Notes arrow_drop_up
Related Articles

Start Your Coding Journey Now!