ganeshmaax
ganeshmaax

Reputation: 59

Get domain name from the email list

Get domain name from the email list
Hi, I have a list of email id from which i have to get the domain name.

For simple email like [email protected], I have done the code part from which I got the domain.
But for emails like [email protected] (actual domain name is ibm.com), I am unable to get the domain.

String domainName = "";
String[] parts = email.split("@");
if(parts.length == 2) 
    domainName = parts[1];

How do I split or do a regular expression to get the domain name?

Upvotes: 2

Views: 19189

Answers (4)

Honza Zidek
Honza Zidek

Reputation: 20026

Using StringUtils.substringAfter() from Apache Commons Lang, which is quite a standard, you can have it more elegant, plus you have null-handling and missing-@-handling for free.

public String extractDomain(String email) {
    return StringUtils.substringAfter(email, "@");
}

Gets the substring after the first occurrence of a separator. The separator is not returned.

You may need to add the Maven dependency, but in Spring Boot it is already included.

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.12.0</version>   <!-- the current version as of today -->
</dependency>

Upvotes: 6

streetturtle
streetturtle

Reputation: 5850

Just in case anybody's still wondering how to do it, here is another way, which supports input strings without '@' character:

private Optional<String> extractEmailDomain(String emailAddress) {
    int atIdx = emailAddress.indexOf("@");
    if (atIdx > 0) {
        return Optional.of(emailAddress.substring(atIdx + 1));
    }

    return Optional.empty();
}

Upvotes: 1

Jacques Ramsden
Jacques Ramsden

Reputation: 871

You could try the following

(?<=@)[^.]+(?=\.)

This will give back the domain name only with no trailing suffex e.g. [email protected] will return domain

(?<=@)[a-zA-Z0-9\.]+(?<=)

This will give back the domain and is suffix e.e [email protected] will return domain.com or [email protected] will return 192.168.0.1

To explain how it works

?<=

Positive Look behind

@

matches the character @ literally (case sensitive)

Match a single character [a-zA-Z0-9.]

+

Quantifier — Matches between one and unlimited times, as many times as possible, giving back as needed (greedy)

.

matches the character . literally (case sensitive)

?<=

Positive Look behind

and by not giving a value to look behind null is assumed which , matches any position

For more info on Java Regex please see Tutorials Point

Upvotes: 1

String#substring() is more than fine, splitting is generating an array for nothing....(kind of waste of resources...)

define a method (is cleaner going that way...)

public String getEmailDomain(String someEmail)
{
    return  someEmail.substring(someEmail.indexOf("@") + 1);
}

Upvotes: 9

Related Questions