Let's consider the following example:
String s = str.replaceAll("regexp", "$1");
Some languages allow us to specify \U$1
in place of $1
which converts matched groups with uppercase letters. How can I achieve the same using Java?
I know we can use Pattern
class and get the group and convert it to uppercase, but that's not what I am looking for. I want to just change $1
with something that gets the job done.
I have also tried:
String s = str.replaceAll("regexp", "$1".toUpperCase());
But it looks like "$1".toUpperCase()
is "$1"
and not the match. I confirmed it using:
String s = str.replaceAll("regexp", method("$1"));
// method declared as method()
private static String method(String s) {
System.out.println(s); // prints "$1"
return s;
}
Is it even allowed in Java?
EDIT:
String s = "abc";
System.out.println(s.replaceAll("(a)", "$1")); // should print "Abc"
EDIT FOR POSSIBLE DUPE:
I am not looking for way using m.group()
, is it possible using something like \U$1
in place of $1
with replaceAll()