开发者

Regex for url domain

开发者 https://www.devze.com 2023-01-01 11:59 出处:网络
How do i match from these urls: http://foo.bar.com http:/开发者_运维问答/bar.com foo.bar from the first link andbar from the second link using one single regex?Try this:

How do i match from these urls:

http://foo.bar.com  
http:/开发者_运维问答/bar.com

foo.bar from the first link and bar from the second link using one single regex?


Try this:

^http://(.*)\.com$

Here's how to use it from Python:

import re

for url in ['http://foo.bar.com', 'http://bar.com']:
    print re.match('^http://(.*)\.com$', url).group(1)

Output:

foo.bar
bar


You didn't mention your language. In Ruby,

>> s = 'http://foo.bar.com'
>> s =~ /\/\/(.*)\./
>> $1
=> "foo.bar"


In Javascript, you will need to use the same regex as given by Mark Byers, no need to change anything:

var p = new RegExp("^http://(.*)\.com");

var out = p.exec(string_var_here);
if(out != null) {
  var str = out[1];
}
0

精彩评论

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