As Mat said, the best way to solve this problem is with URLEncoder. However, if you insist on using regex, then see the sample code in the documentation for java.util.regex.Matcher.appendReplacement
:
Pattern p = Pattern.compile("cat");
Matcher m = p.matcher("one cat two cats in the yard");
StringBuffer sb = new StringBuffer();
while (m.find()) {
m.appendReplacement(sb, "dog");
}
m.appendTail(sb);
System.out.println(sb.toString());
Within the loop, you can use m.group()
to see what substring matched and then do a custom substitution based on that. This technique can be used for replacing ${variables} by looking them up in a map, etc.