首页 > 解决方案 > 正则表达式将字符串中的一组小写字母转换为大写字母

问题描述

有人可以告诉我如何编写一个正则表达式,将字符串中的所有“aeiou”字符替换为“AEIOU”等大写字母,反之亦然?

我想使用 java String 类的 replaceAll 方法,但不确定正则表达式。

标签: javastring-formatting

解决方案


这可能是解决方案。

在我看来,它必须有 Java 9 才能使用 replaceAll 方法。阅读此使用 Java 和 RegEx 转换字符串中的大小写

public class Main {
public static final String EXAMPLE_TEST = "This is my small example string which     I'm going to use for pattern matching.";

public static void main(String[] args)  {

    char [] chars = EXAMPLE_TEST.toCharArray(); // trasform your string in a    char array
    Pattern pattern = Pattern.compile("[aeiou]"); // compile your pattern
    Matcher matcher = pattern.matcher(EXAMPLE_TEST); // create a matcher
    while (matcher.find()) {
        int index = matcher.start(); //index where match exist
        chars[index] =  Character.toUpperCase(chars[index]); // change char array where match

    }
        String s = new String(chars); // obtain your new string :-)
    //ThIs Is my smAll ExAmplE strIng whIch I'm gOIng tO UsE fOr pAttErn mAtchIng.
    System.out.println(s);
}
}

推荐阅读