说我有这样的字符串: "http://something.example.com/directory/"
我想要做的是解析这个字符串,并"something"从字符串中提取.
第一步,显然要检查以确保字符串包含"http://"- 否则,它应该忽略该字符串.
但是,我如何才能"something"在该字符串中提取?假设所有将要评估的字符串将具有类似的结构(即我正在尝试提取URL的子域 - 如果正在检查的字符串确实是有效的URL - 其中有效的开头"http://").
谢谢.
PS我知道如何检查第一部分,即我可以简单地将字符串拆分,"http://"但这并不能解决完整的问题,因为这会产生"http://something.example.com/directory/".我只想要的是"something",没有别的.
我正在尝试将本地子域用于Rails应用程序,因此我在/etc/hosts文件中添加了以下行:
# add 'test' subdomain for localhost
127.0.0.1 test.localhost
Run Code Online (Sandbox Code Playgroud)
现在,我可以将浏览器指向,test.localhost:3000并且可以访问我的Rails应用程序。
但是,Rails或WEBrick会将整个织补唐解释为域:
# logging in the controller
logger.debug("domain: '#{request.domain}', subdomain: '#{request.subdomain}'")
# output in the console
domain: 'test.localhost', subdomain: ''
Run Code Online (Sandbox Code Playgroud)
有没有一种简单的方法可以将WEBrick Rails解释test为子域?
谢谢!
我最终做了before_action一个解决方法。
def set_domain_and_subdomain
@domain = request.domain
@subdomain = request.subdomain
# HACK: force /etc/hosts subdomains
if Rails.env.development?
if m = request.domain.match(/([^\.]+).localhost/)
@subdomain = m[1]
@domain = 'localhost'
end
end
end
Run Code Online (Sandbox Code Playgroud)
但是我仍然很好奇,是否有一种方法可以在我的计算机上实现通用(即在`/ etc / hosts之类的东西中)