fork(76) download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.regex.*;
  4.  
  5. /* Name of the class has to be "Main" only if the class is public. */
  6. class Main
  7. {
  8. public static void main(String[] args) {
  9. // replace with "%" what was matched by group 1
  10. // input: aaa123ccc
  11. // output: %123ccc
  12. System.out.println(replaceGroup("([a-z]+)([0-9]+)([a-z]+)", "aaa123ccc", 1, "%"));
  13.  
  14. // replace with "!!!" what was matched the 4th time by the group 2
  15. // input: a1b2c3d4e5
  16. // output: a1b2c3d!!!e5
  17. System.out.println(replaceGroup("([a-z])(\\d)", "a1b2c3d4e5", 2, 4, "!!!"));
  18. }
  19.  
  20. public static String replaceGroup(String regex, String source,
  21. int groupToReplace, String replacement) {
  22. return replaceGroup(regex, source, groupToReplace, 1, replacement);
  23. }
  24.  
  25. public static String replaceGroup(String regex, String source,
  26. int groupToReplace, int groupOccurrence, String replacement) {
  27. Matcher m = Pattern.compile(regex).matcher(source);
  28. for (int i = 0; i < groupOccurrence; i++) {
  29. if (!m.find()) return source; // pattern not met, may also throw an exception here
  30. }
  31. return new StringBuilder(source)
  32. .replace(m.start(groupToReplace), m.end(groupToReplace), replacement)
  33. .toString();
  34. }
  35. }
Success #stdin #stdout 0.07s 380224KB
stdin
Standard input is empty
stdout
%123ccc
a1b2c3d!!!e5