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

Use Java regular expression RegEx to move all special characters to the end of the string)

The following regular expression matches all special characters, that is, all characters except English letters, spaces, and numbers.

"[^a-zA-Z0-9\\s+]"

To move all special characters to the end of the given line, use this regular expression to match all special characters to an empty string, then concatenate the remaining characters into another string, and finally concatenate these two strings.

Example1

public class RemovingSpecialCharacters {
   public static void main(String args[]) {
      String input = "sample # text * with & special@ characters";
      String regex = "[^a-zA-Z0-9\\s+];
      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 special characters#*&@

Example2

The following is a Java program that uses the Regex package methods to move special characters in 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 # text * with & special@ characters";
      String regex = "[^a-zA-Z0-9\\s+];
      String specialChars = "";
      System.out.println("Input string: 
"+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: 
"+ sb.toString();+specialChars );
   }
}

Output result

Input string:
sample # text * with & special@ characters
Result:
sample text with special characters#*&@