只需在一個側面說明逃脫點,而哈姆扎的答案適用於當前的示例代碼,如果您需要確保域名也是有效的,你可能想嘗試不同的方法,因爲[^.\s]+
將匹配ANY字符不是空格或.
(例如,該正則表達式將匹配jk&^%&*(l.example.com
作爲「有效」子域)。
由於域名值的有效字符遠少於無效字符,因此您可以考慮對正則表達式使用「加法」方法,而不是減法。這種模式可能是您尋找有效域名的那個:/(?:[\s.])([a-z0-9][a-z0-9-]+[a-z0-9]\.example\.com)/gi
將其分解多一點。 。 。
(?:[\s.])
- 這將標誌着loweset級子域名的開始
([a-z0-9][a-z0-9-]+[a-z0-9]\.example\.com)
空間或.
匹配 - 這捕獲一組字母,數字或破折號,必須開始並以字母或數字結束(域名規則),然後是域名example.com
。
gi
- 使得正則表達式的貪婪和不區分大小寫
在這一點上,它只是抓住了比賽的問題。由於.match()
不正規表達式「非捕獲組」發揮出色,使用.exec()
代替:
var domainString = "test foo abc.def.example.com bar ghi.jkl.example.com def";
var regDomainPattern = /(?:[\s.])([a-z0-9][a-z0-9-]+[a-z0-9]\.example\.com)/gi;
var aMatchedDomainStrings = [];
var patternMatch;
// loop through as long as .exec() still gets a match, and take the second index of the result (the one that ignores the non-capturing groups)
while (null != (patternMatch = regDomainPattern.exec(domainString))) {
aMatchedDomainStrings.push(patternMatch[1]);
}
此時aMatchedDomainStrings
應該包含所有有效,第一級,子域。
var domainString = "test foo abc.def.example.com bar ghi.jkl.example.com def";
。 。 。應該讓你:def.example.com
和jkl.example.com
,而:
var domainString = "test foo abc.def.example.com bar ghi.jk&^%&*(l.example.com def";
。 。 。應該只給你:def.example.com
我認爲你的意思是'(?<!\。)'而不是'[!?\。]''。 '(?<!)'是一個負面反序,不幸的是它在Javascript中不被支持。 ''[!?\。]'會匹配'!'或'?'或'.',基本上和'(?:!| \?| \。)'相同。 – HamZa