Skip to content

Instantly share code, notes, and snippets.

@mohnish82
Created October 17, 2020 18:02
Show Gist options
  • Save mohnish82/0863e80eeb442fc0c24b9c4460316da2 to your computer and use it in GitHub Desktop.
Save mohnish82/0863e80eeb442fc0c24b9c4460316da2 to your computer and use it in GitHub Desktop.
Java regex search & replace using backreference
Strig input = "_ab__f_";
//Pattern p = Pattern.compile("_+(.)", Pattern.DOTALL);
// pattern with named backreference i.e. (?<firstElement>)
Pattern p = Pattern.compile("_+(?<firstElement>.)", Pattern.DOTALL);
Matcher m = p.matcher(input);
StringBuffer buff = new StringBuffer();
while(m.find()) {
// m.appendReplacement(buff, m.group(1).toUpperCase());
m.appendReplacement(buff, m.group("firstElement").toUpperCase());
}
System.out.printf("Result: %s --> %s", input, buff);
// Result: _ab__f_ --> AbF
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment