Ranjit
Ranjit

Reputation: 5150

find out the domain from an emailId through regex in java

Suppose the email Id is [email protected] and i need to extract the domain name(i.e xyz) from this. I'm fully new in regex. By googled a little I find out a possible solution from this conversation . And tried something like:

 if("[email protected]".matches(".*\\xyz\\b.*")){
     //true
 }

But it didn't work for me. Is there any solutions for this.

Upvotes: 2

Views: 1962

Answers (1)

zx81
zx81

Reputation: 41838

At the simplest, you can use this regex:

(?<=@)\S+

See demo.

  • (?<=@) is a lookbehind that checks that what precedes is a @
  • \S+ matches all chars that are not white-space characters

In Java, you could do this (among several ways to do it):

Pattern regex = Pattern.compile("(?<=@)\\S+");
Matcher regexMatcher = regex.matcher(subjectString);
if (regexMatcher.find()) {
 ResultString = regexMatcher.group();
    } 

Notes

\S+ works for the string you presented, but it is a "rough tool" that can match all kinds of characters. If you wanted something more specific, you could replace the \S+ with this:

(?i)\b([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}\b

This is an expression from the RegexBuddy library for a domain name. There are thousands of ways of matching a domain name. In your case, if you are sure you are getting an email address, the regex I gave you should work just fine.

Reference

Upvotes: 7

Related Questions