นิพจน์ทั่วไปต่อไปนี้จะจับคู่อักขระพิเศษทั้งหมด เช่น อักขระทั้งหมด ยกเว้นช่องว่างและตัวเลขตัวอักษรภาษาอังกฤษ
"[^a-zA-Z0-9\\s+]"
หากต้องการย้ายอักขระพิเศษทั้งหมดไปที่ท้ายบรรทัดที่กำหนด ให้จับคู่อักขระพิเศษทั้งหมดโดยใช้ regex นี้ต่อเข้ากับสตริงว่างและเชื่อมอักขระที่เหลือกับสตริงอื่นในขั้นสุดท้าย เชื่อมสองสตริงนี้เข้าด้วยกัน
ตัวอย่างที่ 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#*&@