Ruby Regex从电子邮件地址提取域

时间:2022-09-13 11:10:58

I have no real previous experience using regex, just saying. I want to extract domain names from email addresses with the below format.

我没有真正使用regex的经验,只是说。我想从以下格式的电子邮件地址中提取域名。

richardc@mydomain.com so that the regex returns just: mydomain

richardc@dommyain.com使regex返回:mydomain

With an explanation of how/why it works if possible! Cheers

如果可能的话,解释一下它是如何工作的。干杯

1 个解决方案

#1


6  

Here capturing (...) the domain name in group \1 and replace the whole string with that capture, which yields the domain name only at the end.

在这里捕获(…)在group \1中的域名,并将整个字符串替换为该捕获,只在最后生成域名。

email = 'richardc@mydomain.com'
domain = email.gsub(/.+@([^.]+).+/, '\1')
# => mydomain

.+ means any character(except \n). So its basically matching the whole email string, and capturing the domain name using ([^.]+) [means anything but dot]

.+表示任何字符(\n除外)。所以基本上匹配整个邮件字符串,获取域名使用([^]+)(意味着除了点)

#1


6  

Here capturing (...) the domain name in group \1 and replace the whole string with that capture, which yields the domain name only at the end.

在这里捕获(…)在group \1中的域名,并将整个字符串替换为该捕获,只在最后生成域名。

email = 'richardc@mydomain.com'
domain = email.gsub(/.+@([^.]+).+/, '\1')
# => mydomain

.+ means any character(except \n). So its basically matching the whole email string, and capturing the domain name using ([^.]+) [means anything but dot]

.+表示任何字符(\n除外)。所以基本上匹配整个邮件字符串,获取域名使用([^]+)(意味着除了点)