If you are being passed a url as a String and want to extract the context root of that application, you can use this regex to extract it. It will work for full urls or relative urls that begin with the context root.
url.replaceAll("^(.*\\/\\/)?.*?\\/(.+?)\\/.*|\\/(.+)$", "$2$3")