Vamshi
Vamshi

Reputation: 11

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

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.

Upvotes: 0

Views: 32

Answers (2)

Unmitigated
Unmitigated

Reputation: 89442

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

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

Upvotes: 2

tostao
tostao

Reputation: 3068

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

will print: HELLO WORLD!

Upvotes: 2

Related Questions