title: Regular expression for valid subdomain in Ruby
body: <p>I'm attempting to validate a string of user input that will be used as a subdomain. The rules are as follows:</p>
  
  <ol>
  <li>Between 1 and 63 characters in length (I take 63 from the number of characters Google Chrome appears to allow in a subdomain, not sure if it's actually a server directive. If you have better advice on valid max length, I'm interested in hearing it)</li>
  <li>May contain a-zA-Z0-9, hyphen, underscore</li>
  <li>May not begin or end with a hyphen or underscore</li>
  </ol>
  
  <p>EDIT: From input below, I've added the following:
  4. Should not contain consecutive hyphens or underscores.</p>
  
  <p>Examples:</p>
  
  <pre><code>a =&gt; valid
  0 =&gt; valid
  - =&gt; not valid
  _ =&gt; not valid
  a- =&gt; not valid
  -a =&gt; not valid
  a_ =&gt; not valid
  _a =&gt; not valid
  aa =&gt; valid
  aaa =&gt; valid
  a-a-a =&gt; valid
  0-a =&gt; valid
  a&amp;a =&gt; not valid
  a-_0 =&gt; not valid
  a--a =&gt; not valid
  aaa- =&gt; not valid
  </code></pre>
  
  <p>My issue is I'm not sure how to specify with a RegEx that the string is allowed to be only one character, while also specifying that it may not begin or end with a hyphen or underscore.</p>
  
  <p>Thanks!</p>