Subexpression "[ ]" จับคู่ตัวอักษรที่ระบุใน braces ทั้งหมด ดังนั้น เพื่อย้ายตัวอักษรพิมพ์ใหญ่ทั้งหมดไปยังท้ายสตริง:
วนลูปผ่านทุกตัวอักษรในสตริงที่กำหนด
จับคู่ตัวอักษรพิมพ์ใหญ่ทั้งหมดในสตริงที่กำหนดโดยใช้ regular expression
"[A-Z]"ต่อตัวอักษรพิเศษและตัวอักษรที่เหลืออยู่เป็นสตริงสองสตริงที่แตกต่างกัน
สุดท้าย ให้ต่อสตริงตัวอักษรพิเศษเข้ากับอีกสตริงหนึ่ง
ตัวอย่างที่ 1: ใช้ Loop ธรรมดา
public class RemovingSpecialCharacters {
public static void main(String args[]) {
String input = "sample B text C with G upper case LM characters in between";
String regex = "[A-Z]";
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 upper case characters in betweenBCGLM
ตัวอย่างที่ 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 B text C with G upper case LM characters in between";
String regex = "[A-Z]";
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 B text C with G upper case LM characters in between Result: sample text with upper case characters in betweenBCGLM