正则表达式将一组小写字母转换为字符串中的大写字母

时间:2019-04-30 15:10:23

标签: java string-formatting

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

我想使用java String类的replaceAll方法,但不确定regEx。

2 个答案:

答案 0 :(得分:1)

这可能是解决方案。

在我看来,它必须具有Java 9才能使用replaceAll方法。 阅读此Use Java and RegEx to convert casing in a string

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

答案 1 :(得分:0)

您可以使用Pattern和Matcher类,我编写了一个清晰的快速代码(从ascii字母小写字符中减去32将为您提供大写字母,请参阅ascii表)。

    String s = "Anthony";
    Pattern pattern = Pattern.compile("[aeiou]");
    Matcher matcher = pattern.matcher(s);
    String modifiedString = "";
    while(matcher.find())
    {
        modifiedString = s.substring(0, matcher.start()) + (char)(s.charAt(matcher.start()) - 32) + s.substring(matcher.end());
    }
    System.out.println(modifiedString);