Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/59.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 如何从混乱的用户输入中匹配/提取域名?_Ruby On Rails_Ruby_Regex - Fatal编程技术网

Ruby on rails 如何从混乱的用户输入中匹配/提取域名?

Ruby on rails 如何从混乱的用户输入中匹配/提取域名?,ruby-on-rails,ruby,regex,Ruby On Rails,Ruby,Regex,有一个表单字段,用户应以“google.com”的形式输入域名 但是,考虑到困惑的用户,我希望能够将输入清除为“google.com”的确切形式,以防他们在以下情况下键入: http://www.google.com http://google.com google.com/blah www.google.com ..and other incorrect forms 实现这一目标的最佳方式是什么 提前谢谢 这很难。您不仅需要解析许多不同形式的URI,还需要知道如何使用诸如Firefox之类的

有一个表单字段,用户应以“google.com”的形式输入域名

但是,考虑到困惑的用户,我希望能够将输入清除为“google.com”的确切形式,以防他们在以下情况下键入:

http://www.google.com
http://google.com
google.com/blah
www.google.com
..and other incorrect forms
实现这一目标的最佳方式是什么


提前谢谢

这很难。您不仅需要解析许多不同形式的URI,还需要知道如何使用诸如Firefox之类的工具从主机名获取TLD。

这很难。您不仅需要解析许多不同形式的URI,还需要知道如何使用诸如Firefox之类的工具从主机名获取TLD。

您可以编写简单的函数,用正则表达式清除这些URI:

  def foo(s)
    s.gsub(/^(http:\/\/)?(www\.)?/,'').gsub(/\/.*$/,'')
  end
这适用于您给出的所有示例。如果这还不够,请添加更多测试用例:

  def test_foo
    assert_equal 'google.com', foo('http://www.google.com')
    assert_equal 'google.com', foo('http://google.com')
    assert_equal 'google.com', foo('google.com/blah')
    assert_equal 'google.com', foo('www.google.com')
  end

您可以编写一个简单的函数,用正则表达式清除这些内容:

  def foo(s)
    s.gsub(/^(http:\/\/)?(www\.)?/,'').gsub(/\/.*$/,'')
  end
这适用于您给出的所有示例。如果这还不够,请添加更多测试用例:

  def test_foo
    assert_equal 'google.com', foo('http://www.google.com')
    assert_equal 'google.com', foo('http://google.com')
    assert_equal 'google.com', foo('google.com/blah')
    assert_equal 'google.com', foo('www.google.com')
  end

您应该构建您的系统,这个gem将处理URI内容(路径、主机、端口),您只需提供默认方案,即
http

gem安装可寻址

范例

>> uri = Addressable::URI.parse("http://google.com?q=lolcat")
=> #<Addressable::URI:0x80bcf0e0 URI:http://google.com?q=lolcat>
>> [uri.host,uri.path,uri.scheme]
=> ["google.com", "", "http"]
uri=Addressable::uri.parse(“http://google.com?q=lolcat") => # >>[uri.host、uri.path、uri.scheme] =>[“google.com”,“http”]
基本上,您只需检测http://是否存在,如果不存在则添加它,因为URI不会为您猜测它。完成了,再也不用手动处理了

您应该构建您的系统,这个gem将处理URI内容(路径、主机、端口),您只需提供默认方案,即
http

gem安装可寻址

范例

>> uri = Addressable::URI.parse("http://google.com?q=lolcat")
=> #<Addressable::URI:0x80bcf0e0 URI:http://google.com?q=lolcat>
>> [uri.host,uri.path,uri.scheme]
=> ["google.com", "", "http"]
uri=Addressable::uri.parse(“http://google.com?q=lolcat") => # >>[uri.host、uri.path、uri.scheme] =>[“google.com”,“http”]
基本上,您只需检测http://是否存在,如果不存在则添加它,因为URI不会为您猜测它。完成了,再也不用手动处理了

这是一个非常有趣和灵活的解决方案。谢谢。这是一个非常有趣和灵活的解决方案。非常感谢。