如何使用正则表达式选择单词的一部分?

时间:2017-04-28 14:46:09

标签: javascript regex

我有一些文字,我想在其中找到所有电子邮件部分。然后只返回圆顶部分,它应该看起来像:
meth@buisness.com - > buisness.com
yaourt@yoplait.fr - > oplait.fr 我试着这样做:
代码



var text = "I get a mail from meth@buisness.com (by the way I thought its domain was buisness.com), it was sent to yaourt@yoplait.fr, but the guys of gmail.com said we could only trust the yaourt@cesi.fr adress";
function getDomainsOfEmails(text) {
	var regMatch = /@([a-z]+.[a-z]+)/g;
	var regReturn = text.match(regMatch);
	console.log( regReturn);
  return regReturn;
}
getDomainsOfEmails(text);



但我不知道如何从搜索中排除"@"符号。

2 个答案:

答案 0 :(得分:3)

RegExp中的括号创建了cature组。 regexp.exec函数返回一个数组,其中0是整个匹配,然后所有其他单元格从左到右包含捕获组。所以这个:

var reg = /@([a-z0-9-]+\.[a-z]+)/ig;
reg.exec(text);

首次通话时会返回以下内容:

[
  0: "@yoplait.fr"
  1: "yoplait.fr"
]

如果你再次调用它,因为表达式有一个全局标志,它将得到下一个结果:

[
  0: "@buisness.com"
  1: "buisness.com"
]

答案 1 :(得分:-1)

但最好将此分为两部分并获得第二部分。试试这个我希望这是工作

(?<=@)[^.]+(?=\.).*$