นิพจน์ย่อย “[ ] ” ตรงกับอักขระทั้งหมดที่ระบุในวงเล็บปีกกา ดังนั้น เพื่อย้ายตัวอักษรตัวพิมพ์ใหญ่ทั้งหมดไปที่ส่วนท้ายของสตริง −
-
วนซ้ำอักขระทั้งหมดในสตริงที่กำหนด
-
จับคู่อักษรตัวพิมพ์ใหญ่ทั้งหมดในสตริงที่กำหนดโดยใช้นิพจน์ทั่วไป "[A-Z] ".
-
เชื่อมอักขระพิเศษและอักขระที่เหลือเป็นสองสตริงที่ต่างกัน
-
สุดท้าย เชื่อมสตริงอักขระพิเศษกับสตริงอื่น
ตัวอย่างที่ 1
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);
}
} ผลลัพธ์
Result: sample text with upper case characters in betweenBCGLM
ตัวอย่างที่ 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 B text C with G upper case LM characters in between";
String regex = "[A-Z]";
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 B text C with G upper case LM characters in between Result: sample text with upper case characters in betweenBCGLM