Regex replace the substitution string

roundAbout :

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()

Sam :

Since Java 9, we can provide a Function to Matcher#replaceAll(Function<MatchResult,​String> replacer). It is more concise than other answers here. Eg:

Pattern.compile("regexp")
       .matcher(str)
       .replaceAll(mr -> mr.group().toUpperCase());

We can fully customize this behaviour since we have a hold on MatchResult:

Pattern.compile("regexp")
       .matcher(str)
       .replaceAll(mr -> {
                String.format("%s %s", 
                              mr.group(1).toUpperCase),
                              mr.group(2).indent(4);
                   });

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=457055&siteId=1
Recommended