2

Suppose the email Id is abc@xyz.com 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("abc@xyz.com".matches(".*\\xyz\\b.*")){
     //true
 }

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

Community
  • 1
  • 1
Ranjit
  • 5,130
  • 3
  • 30
  • 66
  • please add comments for negative vote..so i can findout my mistake.. – Ranjit Jun 25 '14 at 09:33
  • Your question does not show any serious research effort and is just asking for the codezzz. Also "what you tried" is just garbage and not related to the question. – Theolodis Jun 25 '14 at 09:34
  • @Theolodis i don't find any cause for negative vote in my question.also i don't say you are wrong. i welcome it. – Ranjit Jun 25 '14 at 09:38
  • I do not say that the question is absolutely stupid, but I wouldn't have asked it because it can be solved by googling 5 minutes. – Theolodis Jun 25 '14 at 11:50
  • @Theolodis I accepted my mistake. i will try to ignore such kind of mistakes in future. And thanks for a nice comment. – Ranjit Jun 25 '14 at 12:05
  • You're welcome, a downvote isn't meant to discourage anyway, it is just to signal to other people that the question could possibly not be very interesting. But you got one of a million possible solutions, so good luck ;) – Theolodis Jun 25 '14 at 12:10
  • I found a more constructive way of showing what I meant: if you would for example have written that you did split the string on the `@`, but you want to know if there is a safer/faster/more intuitive way of achieving that with a regex I wouldn't have concluded that you just want the code. But your code sample is really not related to the context of the question... – Theolodis Jun 25 '14 at 13:46

1 Answers1

7

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

zx81
  • 41,100
  • 9
  • 89
  • 105