我们可以使用 Java 中的 Matcher 通过正则表达式替换来更改输入字符串的大小写吗?

问题描述 投票:0回答:2

我想实现类似的目标,

输入:世界你好! 输出:你好世界!

我可以在 Matcher.replaceAll(replacement) 中使用什么替换字符串来实现此目的?

我知道我们可以使用函数引用,但我想使用正则表达式字符串来实现这一点,例如 replaceAll("\U....something...")

我可以看到文本编辑器和perl中使用的一些编译器支持“\U”来转换大小写。

Java 中有类似的东西吗?

我尝试使用 \U 但似乎不支持它。

在 Pattern 类 JavaDoc 中提到“与 Perl 的差异”下不支持 \U。

无法找到更多可用于此目的的内容。

java regex replaceall
2个回答
2
投票
String test = "Hello world!";
System.out.println(test.toUpperCase());

将打印:

HELLO WORLD!


2
投票

您可以将替换函数传递给

Matcher#replaceAll

String res = pattern.matcher(str).replaceAll(mr -> mr.group().toUpperCase());
© www.soinside.com 2019 - 2024. All rights reserved.