English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Use Java RegEx to move all uppercase letters to the end of the string

Subexpression " [] Match all characters specified within the parentheses. Therefore, to move all uppercase letters to the end of the string-

  • Traverse all characters in the given string.

  • Use the regular expression " [AZ] Match all uppercase letters in the given string.

  • Concatenate special characters and the rest of the characters to two different strings.

  • Finally, concatenate the special character string to another string.

Example1

public class RemovingSpecialCharacters {
   public static void main(String args[]) {
      String input = "sample B text C with G uppercase 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

Result: sample text with upper case characters in between BCGLM

Example2

The following is a Java program that uses the Regex package methods to move uppercase letters to the end of a string.

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 uppercase LM characters in between";
      String regex = "[A-Z]";
      String specialChars = "";
      System.out.println("Input string: \n");+input);
      //Create a pattern object
      Pattern pattern = Pattern.compile(regex);
      //Match the compiled pattern in the string
      Matcher matcher = pattern.matcher(input);
      //Create 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 result

Input string:
sample B text C with G uppercase LM characters in between
Result:
sample text with upper case characters in between BCGLM