使用 Java 正则表达式 (RegEx) 将所有特殊字符移动到字符串尾部
以下正则表达式匹配所有特殊字符,即除英语字母、空格和数字以外的所有字符。
"[^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("Result: "+inputData+specialChars);
}
}输出
Result: sample text with special characters#*&@
示例 2
以下是 Java 程序,它使用 Regex 包的方法将字符串的特殊字符移动到末尾。
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 );
}
}输出
Input string: sample # text * with & special@ characters Result: sample text with special characters#*&@
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP