The subexpression “[ ]” matches all the characters specified in the braces. Therefore, to move all the upper case letters to the end of a string −
Iterate through all the characters in the given string.
Match all the upper case letters in the given string using the regular expression "[A-Z]".
Concatenate the special characters and the remaining characters to two different strings.
Finally, concatenate the special characters string to the other string.
Example 1
public class RemovingSpecialCharacters {
public static void main(String args[]) {
String input = "sample B text C with G upper case LM characters in between";
String regex = "[A-Z]";
String specialChars = "";
String inputData = "";
for(int i=0; i< input.length(); i++) {
char ch = input.charAt(i);
if(String.valueOf(ch).matches(regex)) {
specialChars = specialChars + ch;
} else {
inputData = inputData + ch;
}
}
System.out.println("Result: "+inputData+specialChars);
}
}Output
Result: sample text with upper case characters in betweenBCGLM
Example 2
Following is the Java program which moves the upper case letters of a string to its end using the methods of Regex package.
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main(String args[]) {
String input = "sample B text C with G upper case LM characters in between";
String regex = "[A-Z]";
String specialChars = "";
System.out.println("Input string: \n"+input);
//Creating a pattern object
Pattern pattern = Pattern.compile(regex);
//Matching the compiled pattern in the String
Matcher matcher = pattern.matcher(input);
//Creating an empty string buffer
StringBuffer sb = new StringBuffer();
while (matcher.find()) {
specialChars = specialChars+matcher.group();
matcher.appendReplacement(sb, "");
}
matcher.appendTail(sb);
System.out.println("Result: \n"+ sb.toString()+specialChars );
}
}Output
Input string: sample B text C with G upper case LM characters in between Result: sample text with upper case characters in betweenBCGLM