Module: UrlRegex

Defined in:
lib/url_regex.rb,
lib/url_regex/version.rb

Overview

Provides the best known regex for validating and extracting URLs. It uses amazing job done by [Diego Perini](gist.github.com/dperini/729294) and [Mathias Bynens](mathiasbynens.be/demo/url-regex).

Constant Summary collapse

JAVASCRIPT_BASE =
'
(?:\S+(?::\S*)?@)?
(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})
(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])
(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|
(?:(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]-*)*[a-z\u00a1-\uffff0-9]+)*
(?:\.(?:[a-z\u00a1-\uffff]{2,}))\.?)(?::\d{2,5})?(?:[/?#]\S*)?'.gsub(/\s+/, '').freeze
VERSION =
'0.0.4'.freeze

Class Method Summary collapse

Class Method Details

.get(scheme_required: true, mode: :validation) ⇒ Regex

Returns the regex for URLs parsing or validating.

Parameters:

  • scheme_required (Boolean) (defaults to: true)

    will the regex require scheme presence, defaults to true

  • mode (Symbol) (defaults to: :validation)

    purpose of the regex, ‘:validation` or `parsing`, defaults to `:validation`

Returns:

  • (Regex)

    regex for parsing or validating

Raises:

  • (ArgumentError)


12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/url_regex.rb', line 12

def self.get(scheme_required: true, mode: :validation)
  raise ArgumentError, "wrong mode: #{mode}" if MODES.index(mode).nil?

  scheme = scheme_required ? PROTOCOL_IDENTIFIER : PROTOCOL_IDENTIFIER_OPTIONAL

  case mode
  when :validation
    /\A#{scheme} #{BASE}\z/xi
  when :parsing
    /#{scheme} #{BASE}/xi
  when :javascript
    /^#{scheme}#{JAVASCRIPT_BASE}$/
  end
end