title: Java Regex: How to Match URL Path?
body: <p>I am trying to extract the first part of the path of a URL.  For example: from <code>http://foo.com/bar/1/2/3</code> I want to extract <code>bar</code>.  Here is the code I am using:</p>
  
  <pre><code>private static String getFirstPartOfPath(String url)
  {
      Pattern pattern = Pattern.compile("^https?://[^/]+/([^/]+)/*$");
      Matcher matcher = pattern.matcher(url);
      if(matcher.find())
      {
          System.out.println(matcher.group(1));
      }
      return null;
  }
  </code></pre>
  
  <p>However, this does not match the most trivial url listed above, as in  </p>
  
  <pre><code>public static void main(String[] args)
  {
      getFirstPartOfPath("http://foo.com/bar/1/2/3");
  }
  </code></pre>
  
  <p>prints nothing.  At first glance the pattern string seems clear and like it should obviously work.  What is going wrong?</p>