Regular Expression ต่อไปนี้จับคู่ตัวอักษรพิเศษทั้งหมด กล่าวคือ ตัวอักษรทั้งหมดยกเว้นตัวอักษรภาษาอังกฤษ ช่องว่าง และตัวเลข:
"[^a-zA-Z0-9\\s+]"
เพื่อย้ายตัวอักษรพิเศษทั้งหมดไปยังท้ายของบรรทัดที่กำหนด ให้จับคู่ตัวอักษรพิเศษทั้งหมดโดยใช้ regex นี้ ต่อสตริงพวกเขาเข้ากับสตริงว่าง และต่อตัวอักษรที่เหลืออยู่เข้ากับอีกสตริงหนึ่ง สุดท้าย ให้ต่อสตริงทั้งสองนี้เข้าด้วยกัน
ตัวอย่างที่ 1: ใช้ Loop ธรรมดา
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#*&@
ตัวอย่างที่ 2: ใช้ Pattern และ Matcher (java.util.regex)
โปรแกรม 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);
// สร้าง Pattern object
Pattern pattern = Pattern.compile(regex);
// จับคู่ pattern ที่คอมไพล์แล้วในสตริง
Matcher matcher = pattern.matcher(input);
// สร้าง StringBuffer ว่าง
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#*&@