2013-01-16 55 views
0

我嘗試一些事情regex'es,我想知道如何做到以下幾點: 接受:正則表達式 - 可選,需要

http://google.com 
https://google.com 
http://google.com/ 
https://google.com/ 
http://google.com/* 
https://google.com/* 
http://*.google.com 
https://*.google.com 
http://*.google.com/ 
https://*.google.com/ 
http://*.google.com/* 
https://*.google.com/* 

的子域通配符只能包含[AZ] [AZ] [ 0-9]並且是可選的,但是如果它在需要之後存在點。

我就儘可能:

https?://(www.)google.com/ 

但我認爲這是不工作的正確方法......只有WWW。是可用的。 我希望有人能夠給我所需的結果,並解釋它爲什麼這樣工作。

感謝,

丹尼斯

+0

你想要匹配什麼? – nicooga

回答

6

我認爲這可能是你追求的:

https?://([a-zA-Z0-9]+\.)?google\.com(/.*)? 

this site將幫助您驗證的正則表達式。這似乎與您想要的匹配,但您可能希望對最後一部分更具體,因爲.*字面上與任何內容相匹配。

0

作爲POSIX ERE:

https?://(\*|([a-zA-Z0-9]+)\.)?google.com 

(\*|([a-zA-Z0-9]+)\.)部分表明您有一張*或字母數字串,其隨後是一個點。這是可選的,所以後面跟着一個問號。

你也可以用POSIX字符類更換範圍[a-zA-Z0-9][[:alnum:]],贈送:

https?://(\*|([[:alnum:]]+)\.)?google.com 
3
http(s)?://([a-zA-Z0-9]+\.)?google\.com(/.*)? 

[這是rmhartog答案,這看起來是正確的我] 我只是想擴大關於爲什麼 - 這是在問題中提出的。 OP請不要接受我的回答,因爲我只是擴大了前人的回答。

http - This must be an exact match 
(s)? - ? is zero or one time 
:// - This must be an exact match 
( - start of a group 
[a-zA-Z0-9] - Defines a character class that allows any of these characters in it. 
+ - one or more of these characters must be present, empty set is invalid. 
\. - escapes the dot character (usually . is a wildcard in regex) 
)? - end of the group and the group can appear 0 or one time 
google - This must be an exact match 
\. - escapes the dot character (usually . is a wildcard in regex) 
com - This must be an exact match 
( - start of a group 
/ - This must be an exact match 
.* - matches any character 0 or more times (this fits anything you can type) 
)? - end of the group and the group can appear 0 or one time 

我希望這有助於解釋上面的答案,這將是很難適應這一切作爲評論。

+0

我同意,我應該詳細闡述*爲什麼*,謝謝你這麼做!調升。 – rmhartog