2013-01-16 58 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