นิพจน์ปกติ “[a-zA-Z]+” จับคู่ตัวอักษรภาษาอังกฤษหนึ่งตัวขึ้นไป ดังนั้น เพื่อแยกแต่ละคำในสตริงอินพุตที่กำหนด:
- คอมไพล์นิพจน์ดังกล่าวด้วยเมธอด
compile()ของคลาสPattern - รับออบเจ็กต์
Matcherโดยส่งสตริงอินพุตที่ต้องการเป็นพารามิเตอร์ให้เมธอดmatcher()ของคลาสPattern - สุดท้าย สำหรับแต่ละการจับคู่ ให้ดึงตัวอักษรที่จับคู่ได้โดยเรียกเมธอด
group()
ตัวอย่าง
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class EachWordExample { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter sample text: "); String data = sc.nextLine(); String regex = "[a-zA-Z]+"; // สร้างออบเจ็กต์ Pattern Pattern pattern = Pattern.compile(regex); // สร้างออบเจ็กต์ Matcher Matcher matcher = pattern.matcher(data); System.out.println("Words in the given String: "); while(matcher.find()) { System.out.println(matcher.group()+" "); } } }ผลลัพธ์
Enter sample text: Hello this is a sample text Words in the given String: Hello this is a sample text