ในการตรวจสอบว่าสตริงมีอักขระพิเศษหรือไม่ โปรแกรม Java มีดังต่อไปนี้ −
ตัวอย่าง
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Demo {
public static void main(String[] args){
String my_str="This is a sample only !$@";
Pattern my_pattern = Pattern.compile("[^a-z0-9 ]", Pattern.CASE_INSENSITIVE);
Matcher my_match = my_pattern.matcher(my_str);
boolean check = my_match.find();
if (check)
System.out.println("Special character found in the string");
else
System.out.println("Special character not found in the string");
}
} ผลลัพธ์
Special character found in the string
คลาสชื่อ Demo มีฟังก์ชันหลัก ซึ่งกำหนดสตริงไว้ด้วยอักขระพิเศษบางตัว มีการกำหนดรูปแบบที่ใช้นิพจน์ทั่วไปเพื่อตรวจสอบว่าสตริงมีอักขระพิเศษหรือไม่ มีการกำหนดค่าบูลีนซึ่งจะตรวจสอบเพื่อดูค่าเดียวกัน หากค่าของ Bool เป็นจริง ข้อความความสำเร็จจะถูกพิมพ์ มิฉะนั้น จะแสดงข้อความที่ระบุว่าไม่มีอักขระพิเศษเหล่านี้ปรากฏบนหน้าจอ