import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String[] args) {
final String regex = "^(?>(?'protocol'[a-zA-Z]+)://)?(?'domain'[a-zA-Z0-9.\\-_]*)?(?>:(?'port'\\d{1,5}))?/(?'path'[a-zA-Z0-9_\\-%]+)(?:(?>\\?(?'query'[a-zA-Z0-9_\\-=&%]+))()|(?>#(?'anchor'[a-zA-Z0-9_\\-%]+))()){0,2}$";
final String string = "https://localhost:5000/test?id=10&class=5#header\n"
+ "http://example.com:443/test#header\n"
+ "ws://example.com/test?id=10&class=5\n"
+ "/test?id=10&class=5\n"
+ "/test?t=10\n"
+ "/test#10\n"
+ "/test%20test\n"
+ "/test#10?data=test";
final String subst = "protocol: ${protocol}\\nhost name: ${domain}\\nport: ${port}\\npath: /${path}\\nquery: ${query}\\nanchor: ${anchor}\\n";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);
// The substituted value will be contained in the result variable
final String result = matcher.replaceAll(subst);
System.out.println("Substitution result: " + result);
}
}
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for Java, please visit: https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html