Today Icelab Learned
 about regex

URI regular expressions

Let’s go ahead and write some regex to validate a URI in Ruby:

Good Grief


That’s it!

We can use it like so


If you have a look at the output of URI.regexp in irb, you’ll see the pattern that’s used to match against. It’s relatively complex, but each capture group is documented.

  1. Scheme
  2. Opaque (e.g. scheme:foo/bar)
  3. User Info
  4. Host
  5. Port
  6. Registry
  7. Path
  8. Query
  9. Fragment
irb(main):001:0> URI.regexp.match("")
=> #<MatchData "" 1:"http" 2:nil 3:"username:password" 4:"" 5:"80" 6:nil 7:"/baz.html" 8:"query=string" 9:"frag">