Created
October 17, 2020 18:02
-
-
Save mohnish82/0863e80eeb442fc0c24b9c4460316da2 to your computer and use it in GitHub Desktop.
Java regex search & replace using backreference
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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