Moving all special char to the end of the String using Java Regular Expression RegEx)

JavaObject Oriented ProgrammingProgramming

The following regular expression matches all the special characters i.e. all characters except English alphabet spaces and digits.

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

To move all the special characters to the end of the given line, match all the special characters using this regex concatenate them to an empty string and concatenate remaining characters to another string finally, concatenate these two strings.

Example 1

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: sample text with special characters#*&@

Example 2

Following is the Java program which moves the special characters 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 # text * with & special@ characters";
      String regex = "[^a-zA-Z0-9\\s+]";
      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 # text * with & special@ characters
Result:
sample text with special characters#*&@
raja
Published on 21-Nov-2019 11:56:09
Advertisements