使用 Java 正则表达式 RegEx 将所有特殊字符移动到字符串末尾)

javaobject oriented programmingprogramming更新于 2024/5/11 3:56:17

以下正则表达式匹配所有特殊字符,即除英文字母、空格和数字之外的所有字符。

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

要将所有特殊字符移动到给定行的末尾,请使用此正则表达式匹配所有特殊字符,将它们连接到一个空字符串,并将剩余字符连接到另一个字符串,最后将这两个字符串连接起来。

示例 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("结果: "+inputData+specialChars);
   }
}

输出

结果: sample text with special characters#*&@

示例 2

以下是使用 Regex 包的方法将字符串的特殊字符移动到其末尾的 Java 程序。

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("输入字符串: \n"+input);
      //创建一个 Pattern 对象
      Pattern pattern = Pattern.compile(regex);
      //匹配字符串中的编译模式
      Matcher matcher = pattern.matcher(input);
      //创建一个空的字符串缓冲区
      StringBuffer sb = new StringBuffer();
      while (matcher.find()) {
         specialChars = specialChars+matcher.group();
         matcher.appendReplacement(sb, "");
      }
      matcher.appendTail(sb);
      System.out.println("结果: \n"+ sb.toString()+specialChars );
   }
}

输出

输入字符串:
sample # text * with & special@ characters
结果:
sample text with special characters#*&@

相关文章


有用资源