Could someone please tell me how do I write a Regular expression which replaces all the "aeiou" chars found in my string to capital letters like "AEIOU" and vice versa?
I wanted to use replaceAll method of java String class but not sure about the regEx.
This could be the solution.
It seems to me that it has to have Java 9 to use replaceAll method. Read this 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);
}
}
You can use the Pattern and Matcher class, I wrote a quick code it should be clear (subtracting 32 from an ascii alphabetical lower case char will give you its upper case, see the ascii table).
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.