HackerRank Detect the Email Addresses Solution

Hello Programmers, In this post, you will know how to solve the HackerRank Detect the Email Addresses Solution. This problem is a part of the Regex HackerRank Series.

HackerRank Detect the Email Addresses Solution
HackerRank Detect the Email Addresses Solutions

One more thing to add, don’t directly look for the solutions, first try to solve the problems of Hackerrank by yourself. If you find any difficulty after trying several times, then you can look for solutions.

HackerRank Detect the Email Addresses Solution

Problem

You will be provided with a block of text, spanning not more than hundred lines. Your task is to find the unique e-mail addresses present in the text. You could use Regular Expressions to simplify your task. And remember that the “@” sign can be used for a variety of purposes! Requirements are simplified versus real world. There can be a number of strings separated by dots before and after the “@” symbol. Strings will be made up of characters in the ranges a-z, A-Z, 09, _ (underscore).

Input Format

The first line contains an integer N (N<=100), which is the number of lines present in the text fragment which follows.
From the second line, begins the text fragment (of N lines) in which you need to search for e-mail addresses.

Output Format

All the unique e-mail addresses detected by you, in one line, in lexicographical order, with a semi-colon as the delimiter.

Sample Input

19
HackerRank is more than just a company
We are a tight group of hackers, bootstrappers, entrepreneurial thinkers and innovators. We are building an engaged community of problem solvers. Imagine the intelligence and value that a room would hold if it contained hackers/problem solvers from around the world? We’re building this online.
Hypothesis: Every hacker loves a particular type of challenge presented in a certain set of difficulty. If we build a large collection of real world challenges in different domains with an engaging interface, it is going to be incredible! Join us to create history.
Available Positions
Product Hacker [email protected]
Challenge Curator
Product Evangelist
Product Designer
Content Creator
ACM World Finals Hacker
Backend C++ Hacker
Mail us at [email protected] to chat more. Or you can write to us at [email protected]!
HACKERRANK PERKS
Working for a startup is hard work, but there are plenty of benefits of working for a small, fun, growing team.
[Image] Perk: Get tools for the jobAll the Right ToolsWe know that everyone’s perfect workspace is unique to them. We will get you set up with whatever equipment you need to start hacking – a new 15” Macbook Pro or iMac, or a computer of your choice plus a display if you need it. Additionally, if you require any software or other tools, we’ve got it covered.[Image] Perk: Flexible HoursFlexible HoursBecause we work so hard, we encourage our employees to keep flexible hours and don’t require them to track their time. A morning scrum and open communication ensures that the job gets done on time, and we rely on the honor system so that you can work on your own pace.[Image] Perk: HealthcareWellness SupportTo work hard, you have to be healthy. We will cover your health, dental, and visual insurance with no wait period. That means instant benefits from the day you’re hired.[Image] Perk: Choice of LocationLocation, Location, LocationWe are the first Indian company to be backed by Y-Combinator, and as a result we have a thriving office in Bangalore and a growing office in Mountain View, CA. Depending on your residency or visa status, we will get you situated in one of our two offices, both of which are located in the heart of their country’s tech industry.[Image] Perk: Choice of LocationCreative SupportIf you have a cool side project that you want to launch, we will pay for EC2/heroku servers to get it off the ground. Side projects fuel creativity and learning, which are crucial to the HackerRank culture.
CULTURE
The culture of a startup is reflective of the founders’ DNA. Larry Page & Sergey Brin were PhD’s from Stanford and that’s why Google is filled with high scoring graders from top schools and is very hard to get in if you’re not a CS major. Similarly, the hacker culture at Facebook is inspired by Zuckerberg, a hacker, the design culture by Steve Jobs and so on.
The adjective to describe the environment/founders here is relentless hardworkers. It might be a general trait of a startup but I’m pretty sure it’s a notch higher here and defines the culture. This is what has taken us this far. It’s not working in weekends or allnighters that count, but the effort that goes into building something intellectually engaging for hackers and making it fun is high.
You’ll have to embrace randomness and chaos. There’s some level of discipline (eg: daily scrums) but only so much. We push boundaries everyday, stretch our limits but no one complains because there’s a feeling of doing something great at the end of the day, every single day.

Sample Output

[email protected];[email protected];[email protected]

Ezoicreport this adHackerRank Detect the Email Addresses Solution in Cpp

#include <cmath>
#include <cstdio>
#include <vector>
#include <set>
#include <iostream>
#include <algorithm>
using namespace std;
vector<string> split(string s, char delimiter){
    vector<string> result;
    string t = "";
    for(int i = 0; i < s.length(); i++){
        
        if(s[i] == delimiter || s[i] == '\t'){
            
            if(t!="") {
                result.push_back(t);
                t="";
            }
        }
        else {
            //cout<<s[i];
            t+=s[i];
        }
    }
    if(t!="") result.push_back(t);
    return result;
}
bool isEmail(string s){
    bool email = false;
    int i = 0;
    int len = s.length();
    while(i < len && s[i]!='@')i++;
    if(i!=len) {
        i+=1;
        if(i < len && s[i] != '.') {
            while(i < len && s[i]!='.') i++;
            if(i!=len){
               email = true;
            }
        }
    }
    return email;
}
int main() {
    /* Enter your code here. Read input from STDIN. Print output to STDOUT */ 
    int n;
    cin>>n;
    string s;
    getline(cin,s);
    set<string> emails;
    while(n--){
        getline(cin,s);
        vector<string> spt = split(s,' ');
        for(int i = 0; i < spt.size(); i++){
            //cout<<spt[i]<<endl;
            if(isEmail(spt[i])) {
                int j;
                for(j = spt[i].length() - 1; j>=0; j--) {
                    if(spt[i][j] != '.' && spt[i][j] != '!') break; 
                }
                emails.insert(spt[i].substr(0,j+1));
            }
        }
    }
    string result = "";
    for(set<string>::iterator it = emails.begin(); it != emails.end(); it++){
        result+= *it + ";";
    }
    cout<<result.substr(0,result.length() -1)<<endl;
    return 0;
}

HackerRank Detect the Email Addresses Solution in Java

/**
 * 
 */
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
 * @author Antonio081014
 * @since Sep 19, 2013, 3:46:51 PM
 */
public class Solution {
	public static void main(String[] args) {
		Solution main = new Solution();
		main.run();
		System.exit(0);
	}
	private void run() {
		try {
			BufferedReader in = new BufferedReader(new InputStreamReader(
					System.in));
			HashSet<String> emails = new HashSet<String>();
			int N = Integer.parseInt(in.readLine());
			for (int i = 0; i < N; i++) {
				String[] s = in.readLine().split("\\s");
				for (int j = 0; j < s.length; j++) {
					// s[j] = s[j].replaceAll("[^[email protected]]", "");
					if (isEmail(s[j])) {
						// s[j].replaceAll("(\\b)[\\W]*", "");
						s[j] = trans(s[j]);
						emails.add(s[j]);
					}
				}
			}
			ArrayList<String> list = new ArrayList<String>(emails);
			Collections.sort(list);
			System.out.print(list.get(0));
			for (int i = 1; i < list.size(); i++)
				System.out.print(";" + list.get(i));
			System.out.println();
		} catch (Exception e) {
		}
	}
	private boolean isEmail(String s) {
		// String pattern = "^(\\w)[email protected](\\w)+.(\\w)+[\\W]*";
		// String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
		// + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
		// Pattern VALID_EMAIL_ADDRESS_REGEX = Pattern.compile(
		// "^[A-Z0-9._%+-][email protected][A-Z0-9.-]+\\.[A-Z]{2,6}$",
		// Pattern.CASE_INSENSITIVE);
		Pattern pattern = Pattern
				.compile("[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})");
		Matcher matcher = pattern.matcher(s);
		return matcher.find();
		// return s.matches(EMAIL_PATTERN);
	}
	private String trans(String s) {
		for (int i = s.length() - 1; i >= 0; i--) {
			if ((s.charAt(i) >= 'a' && s.charAt(i) <= 'z')
					|| (s.charAt(i) >= 'A' && s.charAt(i) <= 'Z')
					|| (s.charAt(i) >= '0' && s.charAt(i) <= '9')) {
				return s.substring(0, i + 1);
			} else {
				continue;
			}
		}
		return "";
	}
}

HackerRank Detect the Email Addresses Solution in Python

import sys,re
tc=int(raw_input())
r=re.compile(r"[a-zA-Z_.-0-9+][email protected][a-zA-Z0-9.]+[a-zA-Z]+")
emailIds=[]
lines=[]
for _ in range(tc):
    line=sys.stdin.readline().strip()
    lines.append(line)
for line in lines:
    emails=re.findall(r,line)
    for email in emails:
        emailIds.append(email.strip())
emailIds=list(set(emailIds))
s=''
for e in sorted(emailIds):
    s+=e+';'
print s[:-1]
Ezoicreport this ad

HackerRank Detect the Email Addresses Solution in JavaScript

function processData(input) {
    var match = input.match(/(([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4}))((;(([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})))*)(;{0,1})/gi);
    if(match){
        var str = [];
        for(var i = 0; i < match.length; i++){
            if(str.indexOf(match[i]) == -1){
               str.push(match[i]);
               }
            
        }
        str.sort();
        console.log(str.join(";"));
    }else{
        return 0;
    }
} 
process.stdin.resume();
process.stdin.setEncoding("ascii");
_input = "";
process.stdin.on("data", function (input) {
    _input += input;
});
process.stdin.on("end", function () {
   processData(_input);
});

HackerRank Detect the Email Addresses Solution in PHP

<?php
    $f = fopen("php://stdin", "r");
    $numLines = fgets( $f );
    $total = "";
    while( $line = fgets( $f ) ) $total .= $line;
    $matches = array();
    preg_match_all( '/\b[a-z_-]+[\.a-z_-][email protected][a-z_-]+\.[a-z_-]+[\.a-z_-]+?\b/siU', $total, $matches );
    asort( $matches[ 0 ] );
    $colon = "";
    foreach( array_unique( $matches[ 0 ] ) as $match )
    {
        print $colon . $match;
        $colon =";";
    }
?>

Disclaimer: This problem (Detect the Email Addresses) is generated by HackerRank but the Solution is Provided by BrokenProgrammers. This tutorial is only for Educational and Learning purposes.

Next: HackerRank Detect the Domain Name Solution

Sharing Is Caring

Leave a Comment

Ezoicreport this ad