java 正则 大小写,使用Java和RegEx转换字符串中的大小写

Problem: Turn

"My Testtext TARGETSTRING My Testtext"

into

"My Testtext targetstring My Testtext"

Perl supports the "\L"-operation which can be used in the replacement-string.

The Pattern-Class does not support this operation:

Perl constructs not supported by this class:

[...]

The preprocessing operations \l \u, \L, and \U.

https://docs.oracle.com/javase/10/docs/api/java/util/regex/Pattern.html

解决方案

You can't do this in Java regex. You'd have to manually post-process using String.toUpperCase() and toLowerCase() instead.

Here's an example of how you use regex to find and capitalize words of length at least 3 in a sentence

String text = "no way oh my god it cannot be";

Matcher m = Pattern.compile("\\b\\w{3,}\\b").matcher(text);

StringBuilder sb = new StringBuilder();

int last = 0;

while (m.find()) {

sb.append(text.substring(last, m.start()));

sb.append(m.group(0).toUpperCase());

last = m.end();

}

sb.append(text.substring(last));

System.out.println(sb.toString());

// prints "no WAY oh my GOD it CANNOT be"

Note on appendReplacement and appendTail

Note that the above solution uses substring and manages a tail index, etc. In fact, you can go without these if you use Matcher.appendReplacement and appendTail.

StringBuffer sb = new StringBuffer();

while (m.find()) {

m.appendReplacement(sb, m.group().toUpperCase());

}

m.appendTail(sb);

Note how sb is now a StringBuffer instead of StringBuilder. Until Matcher provides StringBuilder overloads, you're stuck with the slower StringBuffer if you want to use these methods.

It's up to you whether the trade-off in less efficiency for higher readability is worth it or not.

See also

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值