title: (Ruby) regex optional matches
body: <p>I'm writing a Rack app to split hostnames ending with certain prefixes.</p>
  
  <p>For example, the hostname (and port) <code>hello.world.lvh.me:3000</code> needs to be split into tokens <code>hello.world</code>, <code>.lvh.me</code> and <code>:3000</code>. Additionally, the prefix (<code>hello.world</code>), suffix (<code>.lvh.me</code>) and port (<code>:3000</code>) are all optional.</p>
  
  <p>So far, I have a (Ruby) regex that looks like <code>/(.*)(\.lvh\.me)(\:\d+)?/</code>.</p>
  
  <p>This successfully breaks the hostname into component parts but it falls down when one or more of the optional components is missing, e.g. for <code>hello.world:3000</code> or <code>lvh.me:3000</code> or even plain old <code>hello.world</code>.</p>
  
  <p>I've tried adding <code>?</code> to each group to make them optional (<code>/(.*)?(\.lvh\.me)?(\:(\d+)?/</code>) but this invariably ends up with the first group, <code>(.*)</code>, capturing the entire string and stopping there.</p>
  
  <p>My gut feeling is that this is something which might be solved using lookaround but I'll admit this is a totally new realm of regex for me.</p>