title: How to validate and fix invalid number of slashes in URL?
body: <p>I have a code that is not working as expected. The idea is to match a group with slashes from url. The number of slashes should be 1 or more. The algorithm should replace whatever number of slashes with only two. How to fix the code? </p>
  
  <p><strong>HttpURLConverter</strong> </p>
  
  <pre><code>public class HttpURLConverter {
  
      final private String UrlPattern = "((([A-Za-z]{3,9}:(?:\\/\\/)?)(?:[\\-;:&amp;=\\+\\$,\\w]+@)?[A-Za-z0-9\\.\\-]+|(?:www\\.|[\\-;:&amp;=\\+\\$,\\w]+@)[A-Za-z0-9\\.\\-]+)((?:\\/[\\+~%\\/\\.\\w\\-_]*)?\\??(?:[\\-\\+=&amp;;%@\\.\\w_]*)#?(?:[\\.\\!\\/\\\\\\w]*))?)";
  
      URL validateURL(URL url) throws MalformedURLException {
          URL validURL = null;
          if(!Pattern.matches(UrlPattern, url.toString())){
              if(Pattern.matches("(https?|ftp|file):.*", url.toString())){
                  Matcher matcher = Pattern.compile("(https?|ftp|file):(\\/)*([A-za-z0-9\\.\\-?#_]+)([A-za-z0-9\\.\\-?#_\\/]{0,})", Pattern.CASE_INSENSITIVE).matcher(url.toString());
  
                  List&lt;String&gt; allMatches = new ArrayList&lt;String&gt;();
                  while (matcher.find()) {
                         allMatches.add(matcher.group());
                  }
                  if(allMatches.size() &gt; 1){
                      System.out.println(allMatches.get(2));
                      allMatches.set(2, "//"); // replace any number of slashes with only two
                      validURL = new URL(allMatches.toString());
  
                  }else{
                      throw new RuntimeException("Expected slashes after URL shema definition but found none.");
                  }
                  System.out.println(matcher.group(1));
                  System.out.println(matcher.group(2));
                  System.out.println(matcher.group(3));
                      System.out.println(matcher.group(4));
  
              }else{
                  throw new RuntimeException("Given url is not valid. URL shema is not detected");
              }
          }
          return validURL;
      }
  
  }
  </code></pre>
  
  <p><strong>TEST</strong></p>
  
  <pre><code>@Test
      public void testHttpURLConverter2() throws MalformedURLException{
          assertEquals("http://google.com", new HttpURLConverter().validateURL(new URL("http:///google.com")));
      }
  @Test
      public void testHttpURLConverter2() throws MalformedURLException{
          assertEquals("http://google.com", new HttpURLConverter().validateURL(new URL("http:/google.com")));
      }
  </code></pre>