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

问题描述 投票:0回答:2

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

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

java string-formatting
2个回答
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);
}
}

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);
© www.soinside.com 2019 - 2024. All rights reserved.