简体   繁体   English

如何使用正则表达式在@ 等电子邮件域之前和之后抓取内容

[英]How to grab the content before and after an email domain like @ using Regular expression

I am a beginner with regular expressions.我是正则表达式的初学者。 Can anyone please help me to split an email address value which is being entered by the user in the input box.任何人都可以帮我拆分用户在输入框中输入的电子邮件地址值。 For example, from example@abc.com I want to grab " example " and " www.abc.com " using a Regular expression.例如,从example@abc.com我想使用正则表达式获取“ example ”和“ www.abc.com ”。 Currently I am using the following auto complete code:目前我正在使用以下自动完成代码:

var autoCompleteOptions = {
    url: function(phrase) {
      if (phrase.match(/\./)) {
        var newMatch = /^(?:https?:\/\/)?(?:www\.)?(.*)/.exec(phrase);
        phrase = newMatch[1].replace(/\..*/, "");
      }
    },

Suppose the email address entered by a user is stored in a variable email , you can use the following code to split the username and domain part.假设用户输入的电子邮件地址存储在变量email ,可以使用以下代码拆分用户名和域部分。

var email = "example@abc.com";
var match = email.match(/(.*)@(.*)/);
var username = match[1];
var domain = match[2];

If you want to prepend www at the beginning of the domain , add the following line.如果您想在domain的开头添加www ,请添加以下行。

domain = 'www.' + domain;

Alternatively, you can use the JavaScript split() function to implement the same without RegEx.或者,您可以使用 JavaScript split()函数在没有 RegEx 的情况下实现相同的功能。

var email = "example@abc.com";
var parts = email.split('@');
var username = parts[0];
var domain = parts[1];

EDIT编辑

Since the username section in the email can get complex, the above solution can fail in certain cases.由于电子邮件中的用户名部分可能会变得复杂,因此上述解决方案在某些情况下可能会失败。 For complete email validation, complex RegEx need to be used.对于完整的电子邮件验证,需要使用复杂的 RegEx。 Ref参考

However, for the issue that this question raises, a simple solution can be implemented based on the fact that domain names cannon contain @ symbol.但是,对于这个问题提出的问题,可以基于域名炮中包含@符号的事实来实现一个简单的解决方案。

The below code should work in all the cases.下面的代码应该适用于所有情况。

var email = "example@abc.com";
var parts = email.split('@');
//The last part will be the domain
var domain = parts[parts.length - 1];
//Now, remove last part
parts.pop();
//Everything else will be username
var username = parts.join('@');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM