如果比賽不在字符串的開頭失敗
那是因爲^
在比賽的開始:
/(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