/* package whatever; // don't place package name! */
import java.util.regex.*;
/* Name of the class has to be "Main" only if the class is public. */
class Main
{
public static void main
(String[] args
) { // replace with "%" what was matched by group 1
// input: aaa123ccc
// output: %123ccc
System.
out.
println(replaceGroup
("([a-z]+)([0-9]+)([a-z]+)",
"aaa123ccc",
1,
"%"));
// replace with "!!!" what was matched the 4th time by the group 2
// input: a1b2c3d4e5
// output: a1b2c3d!!!e5
System.
out.
println(replaceGroup
("([a-z])(\\d)",
"a1b2c3d4e5",
2,
4,
"!!!")); }
int groupToReplace,
String replacement
) { return replaceGroup(regex, source, groupToReplace, 1, replacement);
}
int groupToReplace,
int groupOccurrence,
String replacement
) { Matcher m = Pattern.compile(regex).matcher(source);
for (int i = 0; i < groupOccurrence; i++) {
if (!m.find()) return source; // pattern not met, may also throw an exception here
}
return new StringBuilder(source)
.replace(m.start(groupToReplace), m.end(groupToReplace), replacement)
.toString();
}
}
LyogcGFja2FnZSB3aGF0ZXZlcjsgLy8gZG9uJ3QgcGxhY2UgcGFja2FnZSBuYW1lISAqLwoKaW1wb3J0IGphdmEudXRpbC5yZWdleC4qOwoKLyogTmFtZSBvZiB0aGUgY2xhc3MgaGFzIHRvIGJlICJNYWluIiBvbmx5IGlmIHRoZSBjbGFzcyBpcyBwdWJsaWMuICovCmNsYXNzIE1haW4KewoJcHVibGljIHN0YXRpYyB2b2lkIG1haW4oU3RyaW5nW10gYXJncykgewoJCS8vIHJlcGxhY2Ugd2l0aCAiJSIgd2hhdCB3YXMgbWF0Y2hlZCBieSBncm91cCAxIAoJCS8vIGlucHV0OiBhYWExMjNjY2MKCQkvLyBvdXRwdXQ6ICUxMjNjY2MKCQlTeXN0ZW0ub3V0LnByaW50bG4ocmVwbGFjZUdyb3VwKCIoW2Etel0rKShbMC05XSspKFthLXpdKykiLCAiYWFhMTIzY2NjIiwgMSwgIiUiKSk7CgkJCgkJLy8gcmVwbGFjZSB3aXRoICIhISEiIHdoYXQgd2FzIG1hdGNoZWQgdGhlIDR0aCB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