简体   繁体   中英

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.

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

will print: HELLO WORLD!

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM