使用Java和RegEx转换字符串中的大小写 [英] Use Java and RegEx to convert casing in a string

查看:653
本文介绍了使用Java和RegEx转换字符串中的大小写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题:转

"My Testtext TARGETSTRING My Testtext" 

进入

"My Testtext targetstring My Testtext"

Perl支持\ L - 操作,可以在替换字符串中使用。

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

Pattern-Class不支持此操作:

The Pattern-Class does not support this operation:


Perl构造不此类支持:
[...]
预处理操作\l \ u,\ L和\U。
https:// docs。 oracle.com/javase/10/docs/api/java/util/regex/Pattern.html


推荐答案

你不能在Java正则表达式中这样做。您必须使用 String.toUpperCase() toLowerCase()

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

这是一个如何使用正则表达式来查找和大写句子中长度至少为3的单词的示例

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"






注意 appendReplacement appendTail



请注意,上面的解决方案使用 substring 并管理 tail 索引等。事实上,你可以去如果你使用 Matcher.appendReplacement appendTail


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);

注意 sb 现在是 StringBuffer 而不是 StringBuilder 。直到 Matcher 提供 StringBuilder 重载,你才会遇到速度较慢的 StringBuffer 如果你想使用这些方法。

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.

  • StringBuilder and StringBuffer in Java

这篇关于使用Java和RegEx转换字符串中的大小写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆