เมทาคแรกเตอร์ “\\s” จับคู่ช่องว่าง และ + บ่งบอกการเกิดขึ้นของช่องว่างหนึ่งครั้งขึ้นไป ดังนั้น นิพจน์ปกติ \\s+ จะจับคู่ตัวอักษรช่องว่างทั้งหมด (ไม่ว่าจะเป็นช่องเดียวหรือหลายช่อง) เพื่อแทนที่ช่องว่างหลายช่องด้วยช่องเดียว:
จับคู่สตริงอินพุตกับนิพจน์ปกติข้างต้นและแทนที่ผลลัพธ์ด้วยช่องว่างเดี่ยว “ ”
ตัวอย่าง 1
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class ReplaceAllExample { public static void main(String args[]) { // อ่านสตริงจากผู้ใช้ System.out.println("Enter a String"); Scanner sc = new Scanner(System.in); String input = sc.nextLine(); String regex = "\\s+"; // คอมไพล์นิพจน์ปกติ Pattern pattern = Pattern.compile(regex); // ดึงออบเจ็กต์ Matcher Matcher matcher = pattern.matcher(input); // แทนที่ตัวอักษรช่องว่างทั้งหมดด้วยช่องเดียว String result = matcher.replaceAll(" "); System.out.print("Text after removing unwanted spaces: \n"+result); } }ผลลัพธ์
Enter a String hello this is a sample text with irregular spaces Text after removing unwanted spaces: hello this is a sample text with irregular spaces
ตัวอย่าง 2
import java.util.Scanner; public class Test { public static void main(String args[]) { // อ่านสตริงจากผู้ใช้ System.out.println("Enter a String"); Scanner sc = new Scanner(System.in); String input = sc.nextLine(); // นิพจน์ปกติสำหรับจับคู่ช่องว่าง String regex = "\\s+"; // แทนที่รูปแบบด้วยช่องว่างเดี่ยว String result = input.replaceAll(regex, " "); System.out.print("Text after removing unwanted spaces: \n"+result); } }ผลลัพธ์
Enter a String hello this is a sample text with irregular spaces Text after removing unwanted spaces: hello this is a sample text with irregular spaces