开发者

Struggle with a Regex to change subdomain, and subsubdomain

I got this from antoher post:

host = ".mylocal.com";
var reg = new RegExp('^https?://(开发者_高级运维[^.]*' + host + ')');
console.log(reg.test('http://www.mylocal.com/'));

but it can only match with www.mylocal.com , whatever.mylocal.com but not two levels down, like dev.www.mylocal.com

i tried writing something else but couldn't get it check the sub -sub . or even 3, 4 levels down. :( how should i write it?

so, what I would like to achieve is:

.local.com
will match:
www.local.com
dev.www.local.com
abc.dev.abc.local.com

and 
www.local.com
will only match 
www.local.com
NOT dev.www.local.com

:) that's more clear


The basic problem is that you want to match all kinds of prefixes, followed by host, if host begins with .; but you want to match host alone if not. This could be done with lookahead assertions, but since you're constructing the regex anyway, it's much simpler to just construct it differently depending on the case. I don't know Javascript, so I'll use pseudocode.

For the first case, we want to match zero or more (non-capturing) groups of non-periods followed by one period, then at least one non-period, all before host. For the second case, we just want to match host.

if host starts with '.':
    var reg = new RegExp('^https?://((?:[^.]+\.)*[^.]+' + host + ')');
else:
    var reg = new RegExp('^https?://(' + host + ')');


not sure what you're trying to do. this regex will match any number of levels:

r = new RegExp("^https?://([^.]+[.])*([^.])+$");
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜