How to replace double slash with single line for url

For a given URL, such as http://google.com//view/All/builds , I want to replace the double slash with a single slash. For example, the above URL should appear as " http://google.com/view/All/builds "

I do not know regular expressions. Can someone help me how can I achieve this using regular expressions.

+8
java regex
source share
4 answers

To avoid replacing the first // in http:// , use the following regex:

 String to = from.replaceAll("(?<!http:)//", "/"); 

PS: if you want to handle https, use (?<!(http:|https:))// instead.

+15
source share
 String to = from.replaceAll("(?<!(http:|https:))[//]+", "/"); 

will match two or more slashes.

+4
source share

Here is the regex:

/(?<=[^:\s])(\/+\/)/g

It finds multiple slashes in storing URLs after the protocol independently of it.
It also handles relative protocol URLs starting with // .

 @Test public void shouldReplaceMultipleSlashes() { assertEquals("http://google.com/?q=hi", replaceMultipleSlashes("http://google.com///?q=hi")); assertEquals("https://google.com/?q=hi", replaceMultipleSlashes("https:////google.com//?q=hi")); assertEquals("//somecdn.com/foo/", replaceMultipleSlashes("//somecdn.com/foo///")); } private static String replaceMultipleSlashes(String url) { return url.replaceAll("(?<=[^:\\s])(\\/+\\/)", "/"); } 

Literally means:

  • (\/+\/) - find the group: /+ one or more slashes, and then / slash
  • (?<=[^:\s]) - which follows the group (* posiive lookbehind) of this (* negative set) [^:\s] , which excludes : colon and \s spaces
  • g - global search flag
+2
source share

I suggest you just use String.replace, which documentation is http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#replace(java.lang.CharSequence , java.lang.CharSequence )

Something like `myString.replace (" // "," / ");

If you want to remove the first appearance:

String[] parts = str.split("//", 2); str = parts[0] + "//" + parts[1].replaceAll("//", "/");

What is the easiest way (without regex). I do not know the regular expression appropriate if there is an expert looking at the stream ....;)

+1
source share

All Articles