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

Time:01-20

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.

CodePudding user response:

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

will print: HELLO WORLD!

CodePudding user response:

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

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