Regular Expression for domain from email address

2019-02-16 14:04发布

Can anyone help me with a regular expression that will return the end part of an email address, after the @ symbol? I'm new to regex, but want to learn how to use it rather than writing inefficient .Net string functions!

E.g. for an input of "test@example.com" I need an output of "example.com".

Cheers! Tim

8条回答
Anthone
2楼-- · 2019-02-16 14:25

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

查看更多
别忘想泡老子
3楼-- · 2019-02-16 14:31
$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()
查看更多
姐就是有狂的资本
4楼-- · 2019-02-16 14:34

@(.*)$

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

查看更多
Luminary・发光体
5楼-- · 2019-02-16 14:39

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.)

查看更多
6楼-- · 2019-02-16 14:39

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.

查看更多
干净又极端
7楼-- · 2019-02-16 14:41

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);
查看更多
登录 后发表回答