Regular Expression for domain from email address

混江龙づ霸主 提交于 2019-12-01 03:12:11

A regular expression is quite heavy machinery for this purpose. Just split the string containing the email address at the @ character, and take the second half. (An email address is guaranteed to contain only one @ character.)

@(.*)$

This will match with the @, then capture everything up until the end of input ($)

This is a general-purpose e-mail matcher:

[a-zA-Z][\w\.-]*[a-zA-Z0-9]@([a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z])

Note that it only captures the domain group; if you use the following, you can capture the part proceeding the @ also:

([a-zA-Z][\w\.-]*[a-zA-Z0-9])@([a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z])

I'm not sure if this meets RFC 2822, but I doubt it.

Wow, all the answers here are not quite right.

An email address can have as many "@" as you want, and the last one isn't necessarily the one before the domain :(

for example, this is a valid email address:

user@example.com(i'm a comment (with an @))

You'd have to be pretty mean to make that your email address though.

So first, parse out any comments at the end.

Then

int atIndex = emailAddress.LastIndexOf("@");
String domainPart = emailAddress.Substring(atIndex + 1);

A simple regex for your input is:

^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$

But, it can be useless when you apply for a broad and heterogeneous domains.

An example is:

^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.(?:[A-Z]{2}|com|org|net|gov|mil|biz|info|mobi|name|aero|jobs|museum)$

But, you can optimize that suffix domains as you need.

But for your suffix needs, you need just:

@.+$

Resources: http://www.regular-expressions.info/email.html

$input=hardiksondagar@gmail.com;
// now you want to fetch gmail from input user PHP's inbuilt function 
preg_match('/@(.*)/', $input, $output);
echo $output[1]; // it'll print "gmail.com"
  • Documentation of function : preg_match()
rajat rastogi

Try this regular expression:

(?<=([\w-\.]@))((?:[\w]+\.)+)([a-zA-Z]{2,4})
(@)(\w+\-|\w+)+(\.)

I am no expert but the above expression is what you need to grab the domain from an e-mail, at least as far as I can tell.

The problem is as pointed out that you grab not only the domain but the "@" and ".". To access the domain name in regex you use "$2"and to preserve the "@" and ".", you could use an expression like:

$1newdomain$3

http://www.regexr.com/

The site above is a good place to try regex to see how and if it works.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!