使用 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#*&@
廣告