The subexpression "[ ]" matches all characters specified in parentheses. So, to move all uppercase letters to the end of the string, you need to perform the following steps:
Iterate through all the characters in the given string.
Use the regular expression "[A-Z]" to match all uppercase letters in the given string.
Concatenate special characters and remaining characters into two different strings.
Finally, concatenate the special character string into another string.
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); } }
Result: sample text with upper case characters in betweenBCGLM
The following is a Java program that uses the Regex package method to move the uppercase letters of a string to the end.
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 ); } }
Input string: sample B text C with G upper case LM characters in between Result: sample text with upper case characters in betweenBCGLM
The above is the detailed content of Move all uppercase letters to end of string using Java regex. For more information, please follow other related articles on the PHP Chinese website!