Can we change case of an input string with regex replacement using Matcher in Java?

34 Views Asked by At

I would like to achieve something like,

Input: Hello world! Output: HELLO WORLD!

What replacement string can I use in Matcher.replaceAll(replacement) to achieve this?

I know we can use a functional reference, but i would like to achieve this using a regex string like replaceAll("\U....something...")

I can see that some compilers used in text editors and perl supports "\U" that converts the case.

Do we have anything equivalent in Java?

I tried using \U but seems it's not supported.

In Pattern class JavaDoc it's mentioned that \U is not supported under "Differences from Perl".

Could not find more what can be used for the purpose.

2

There are 2 best solutions below

0
tostao On
String test = "Hello world!";
System.out.println(test.toUpperCase());

will print: HELLO WORLD!

0
Unmitigated On

You can pass a replacement function to Matcher#replaceAll instead.

String res = pattern.matcher(str).replaceAll(mr -> mr.group().toUpperCase());