使用 Java 和 RegEx 转换字符串中的大小写

发布于 2024-08-31 11:59:16 字数 475 浏览 4 评论 0原文

问题:Turn

"My Testtext TARGETSTRING My Testtext" 

into

"My Testtext targetstring My Testtext"

Perl 支持可在替换字符串中使用的“\L”操作。

模式类不支持此操作:

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

玩世 2024-09-07 11:59:16

您不能在 Java 正则表达式中执行此操作。您必须使用 String.toUpperCase()toLowerCase() 代替。

以下示例展示了如何使用正则表达式查找句子中长度至少为 3 的单词并将其大写。

    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"

注意 appendReplacementappendTail

请注意,上述解决方案使用 substring 并管理 tail 索引等。事实上,如果您使用 Matcher.appendReplacement和appendTail。

    StringBuffer sb = new StringBuffer();
    while (m.find()) {
        m.appendReplacement(sb, m.group().toUpperCase());
    }
    m.appendTail(sb);

请注意 sb 现在如何成为 StringBuffer 而不是 StringBuilder。在 Matcher 提供 StringBuilder 重载之前,如果您想使用这些方法,您将不得不使用较慢的 StringBuffer

以较低的效率换取较高的可读性是否值得,这取决于您。

另请参阅

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

赏烟花じ飞满天 2024-09-07 11:59:16

Java9+

从 Java 9+ 开始,您可以使用 Matcher::replaceAll 您可以在其中使用 Function 例如,我们使用 多基因润滑剂

String text = "this is just a test which upper all short words";
String regex = "\\b\\w{0,3}\\b";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(text);
String result = matcher.replaceAll(matche -> matche.group().toUpperCase());

System.out.println(result);

或者只是:

String result = Pattern.compile(regex)
        .matcher(text)
        .replaceAll(matche -> matche.group().toUpperCase());

输出

this IS just A test which upper ALL short words
     ^^      ^                  ^^^

Java9+

From Java 9+ you can use Matcher::replaceAll where you can use a Function<MatchResult, String> for example we use the example of polygenelubricants :

String text = "this is just a test which upper all short words";
String regex = "\\b\\w{0,3}\\b";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(text);
String result = matcher.replaceAll(matche -> matche.group().toUpperCase());

System.out.println(result);

Or Just :

String result = Pattern.compile(regex)
        .matcher(text)
        .replaceAll(matche -> matche.group().toUpperCase());

Output

this IS just A test which upper ALL short words
     ^^      ^                  ^^^
傲娇萝莉攻 2024-09-07 11:59:16

要在正则表达式级别执行此操作,您必须使用 \U 打开大写模式,并使用 \E 将其关闭。以下是如何在 IntelliJ IDEA find-and-replace 对话框中使用此功能的示例,该对话框将类字段集转换为 JUnit 断言(在 IDE 工具提示中是 find-and-replace 的结果) 转换):

在此处输入图像描述

To do this on regexp level you have to use \U to switch on uppercase mode and \E to switch it off. Here is an example how to use this feature in IntelliJ IDEA find-and-replace dialog which transforms set of class fields to JUnit assertions (at IDE tooltip is a result of find-and-replace transformation):

enter image description here

早乙女 2024-09-07 11:59:16

您可以使用 正则表达式捕获组 (如果您确实需要使用正则表达式,即意思是“TARGETSTRING”足够复杂并且足够“规则”,足以证明被正则表达式检测到是合理的)。
然后,您可以将 toLowerCase() 应用于组 #1。

import java.util.regex.*;

public class TargetToLowerCase {

  public static void main(String[] args) {
    StringBuilder sb= new StringBuilder(
            "my testtext TARGETSTRING my testtext");
    System.out.println(sb);
    String regex= "TARGETSTRING ";
    Pattern p = Pattern.compile(regex); // Create the pattern.
    Matcher matcher = p.matcher(sb); // Create the matcher.
    while (matcher.find()) {
      String buf= sb.substring(matcher.start(), matcher.end()).toLowerCase();
      sb.replace(matcher.start(), matcher.end(), buf);
    }
    System.out.println(sb);
  }
}

You could use the regexp capturing group (if you really need to use regex, that is, meaning if "TARGETSTRING" is complex enough and "regular" enough to justify being detected by a regex).
You would then apply toLowerCase() to the group #1.

import java.util.regex.*;

public class TargetToLowerCase {

  public static void main(String[] args) {
    StringBuilder sb= new StringBuilder(
            "my testtext TARGETSTRING my testtext");
    System.out.println(sb);
    String regex= "TARGETSTRING ";
    Pattern p = Pattern.compile(regex); // Create the pattern.
    Matcher matcher = p.matcher(sb); // Create the matcher.
    while (matcher.find()) {
      String buf= sb.substring(matcher.start(), matcher.end()).toLowerCase();
      sb.replace(matcher.start(), matcher.end(), buf);
    }
    System.out.println(sb);
  }
}
染火枫林 2024-09-07 11:59:16

Java 8”中的这个转换函数怎么样?

/**
 * Searches the given pattern in the given src string and applies the txr to the
 * matches
 * 
 * @param src     The string to be converted
 * @param pattern the pattern for which the transformers to be applied.
 * @param txr     The transformers for the mathed patterns.
 * @return The result after applying the transformation.
 */
private static String fromTo(String src, String pattern, Function<String, String> txr) {
    Matcher m = Pattern.compile(pattern).matcher(src);

    StringBuilder sb = new StringBuilder();
    int last = 0;

    while (m.find()) {
        sb.append(src.substring(last, m.start()));
        sb.append(txr.apply(m.group(0)));
        last = m.end();
    }
    sb.append(src.substring(last));
    return sb.toString();
}

How about this transformation function in "Java 8"

/**
 * Searches the given pattern in the given src string and applies the txr to the
 * matches
 * 
 * @param src     The string to be converted
 * @param pattern the pattern for which the transformers to be applied.
 * @param txr     The transformers for the mathed patterns.
 * @return The result after applying the transformation.
 */
private static String fromTo(String src, String pattern, Function<String, String> txr) {
    Matcher m = Pattern.compile(pattern).matcher(src);

    StringBuilder sb = new StringBuilder();
    int last = 0;

    while (m.find()) {
        sb.append(src.substring(last, m.start()));
        sb.append(txr.apply(m.group(0)));
        last = m.end();
    }
    sb.append(src.substring(last));
    return sb.toString();
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文