如果比赛不在字符串的开头失败
那是因为^
在比赛的开始:
/(www\.)?([^@])([a-z]*\.)(com|net|edu|org)(\.au)?(\/\S*)?$/g
js> "www.foobar.com".match(/(www\.)?([^@])([a-z]*\.)(com|net|edu|org)(\.au)?(\/\S*)?$/g)
["www.foobar.com"]
js> "aoeuaoeu foobar.com".match(/(www\.)?([^@])([a-z]*\.)(com|net|edu|org)(\.au)?(\/\S*)?$/g)
[" foobar.com"]
js> "[email protected] foobar.com".match(/(www\.)?([^@])([a-z]*\.)(com|net|edu|org)(\.au)?(\/\S*)?$/g)
[" foobar.com"]
js> "[email protected] [email protected]".match(/(www\.)?([^@])([a-z]*\.)(com|net|edu|org)(\.au)?(\/\S*)?$/g)
["foobar.com"]
虽然它仍然匹配域之前的空间。这是对域的错误假设...
xyz.example.org
是与您的正则表达式不匹配的有效域;
www.3x4mpl3.org
是与您的正则表达式不匹配的有效域;
example.co.uk
是与您的正则表达式不匹配的有效域;
ουτοπία.δπθ.gr
是与您的正则表达式不匹配的有效域。
什么定义了合法域名?它只是由点分隔的一系列utf-8字符。它不能有两个点,并且规范名称是\w\.\w\w
(因为我不认为一个字母tld存在)。
虽然,我会做的方式是简单地匹配一切看起来像域,采取一切,是文本用点分隔使用单词边界(\b
):
/\b(\w+\.)+\w+\b/g
js> "aoe toto.example.org uaoeu foo.bar aoeuaoeu".match(/\b(\w+\.)+\w+\b/g)
["toto.example.org", "foo.bar"]
js> "aoe [email protected] toto.example.org uaoeu foo.bar aoeuaoeu".match(/\b(\w+\.)+\w+\b/g)
["example.org", "toto.example.org", "foo.bar"]
js> "aoe [email protected] toto.example.org uaoeu foo.bar aoeuaoeu f00bar.com".match(/\b(\w+\.)+\w+\b/g)
["example.org", "toto.example.org", "foo.bar", "f00bar.com"]
然后进行第二轮检查域是否确实存在或不在发现的域列表中。缺点是JavaScript中的正则表达式无法检查unicode字符,并且\b
或\w
将不接受ουτοπία.δπθ.gr
作为有效的域名。
在ES6,还有的/u
modifier,这应与最新的浏览器中工作(但没有,我迄今已检测):
"ουτοπία.δπθ.gr aoe [email protected] toto.example.org uaoeu foo.bar aoeuaoeu".match(/\b(\w+\.)+\w+\b/gu)
编辑:
负回顾后解决它 - 但显然不在JS中。
是的,它会:跳过所有的电子邮件地址,这里的落后执行正则表达式的工作看:
/(?![^@])?\b(\w+\.)+\w+\b/g
js> "aoe [email protected] toto.example.org uaoeu foo.bar aoeuaoeu f00bar.com".match(/(?<![^@])?\b(\w+\.)+\w+\b/g)
["toto.example.org", "foo.bar", "f00bar.com"]
尽管它同样为Unicode ...它”即将在那里在JS很快...
唯一的方法就是,实际上保留@
在匹配的正则表达式,并放弃任何匹配包含一个@:
js> "toto.net aoe [email protected] toto.example.org uaoeu foo.bar aoeuaoeu f00bar.com".match(/@?\b\w+\.+\w+\b/g).map(function (x) { if (!x.match(/@/)) return x })
["toto.net", (void 0), "toto.example", "foo.bar", "f00bar.com"]
或使用来自ES6/JS1.7新的列表理解,这应该是没有在现代浏览器...
[x for x of "toto.net aoe [email protected] toto.example.org uaoeu foo.bar aoeuaoeu f00bar.com".match(/@?\b\w+\.+\w+\b/g) if (!x.match(/@/))];
一个最后更新:
/@?\b(\w*[^\W\d]+\w*\.+)+[^\W\d_]{2,}\b/g
> "x.y tot.toc.toc $11.00 11.com 11foo.com toto.11 toto.net aoe [email protected] toto.example.org uaoeu foo.bar aoeuaoeu f00bar.com".match(/@?\b(\w*[^\W\d]+\w*\.+)+[^\W\d_]{2,}\b/g).filter(function (x) { if (!x.match(/@/)) return x })
[ 'tot.toc.toc',
'11foo.com',
'toto.net',
'toto.example.org',
'foo.bar',
'f00bar.com' ]
This [question](http://stackoverflow.com/questions/641407/javascript-negative-lookbehind-equivalent)* may * help。 – merlin2011
备注:您是否知道有大量新TLD可用或即将可用? – Marty
也许你可以通过http://regexr.com/ – HJ05