2016-03-04 78 views
1

匹配目前我使用下面的正則表達式匹配的URL正則表達式,而不子

/(([\w]+:)?\/\/)?(([\d\w]|%[a-fA-f\d]{2,2})+(:([\d\w]|%[a-fA-f\d]{2,2})+)[email protected])?([\d\w][-\d\w]{0,253}[\d\w]\.)+[\w]{2,63}(:[\d]+)?(\/([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)*(\?(&?([-+_~.\d\w]|%[a-fA-f\d]{2,2})=?)*)?(#([-+_~.\d\w]|%[a-fA-f\d]{2,2})*)?/ 

我想知道怎樣才能將它修改爲只匹配上的域名沒有子域。

例如

http://thisiatest.com/ -> Good 
thisisatest.com -> Good 
http://thisiatest.com -> Good 
http://thisisatest.com/folder/ -> Bad 
thisisatest.com/folder/ -> Bad 

回答

1

我覺得你的正則表達式可以簡化爲這樣:

^(?:\S+://)?[^/]+/?$ 

RegEx Demo

0

以下的正則表達式也值得一試:

(?:https?://)?([^/\s]+\.[^/\s]+)/?(?:\s|$) 

Here is the Demo.

說明:

(?:https?://)?   non-capturing group starts 
         match http:// or https:// zero or one time 
(      capturing group starts 
[^/\s]+     match characters except/and space 
         1 or more times 
\.      literally match dot (.) 
[^/\s]+     match characters except/and space 
         1 or more times 
)      capturing group ends 
/?      match/zero or one time  
(?:\s|$)    non-capturing group 
         assert any white space or end of line