คลาส Pattern ของแพ็กเกจ java.util.regex เป็น compiled representation ของ regular expression
เมธอด splitAsStream() ของคลาสนี้รับ object CharSequence ที่แทนสตริงอินพุตเป็นพารามิเตอร์ และ ที่แต่ละ match จะแยกสตริงที่กำหนดเป็น substring ใหม่ และคืนค่าผลลัพธ์เป็น stream ที่เก็บ substring ทั้งหมด
ตัวอย่าง
import java.util.regex.Pattern;
import java.util.stream.Stream;
public class SplitAsStreamMethodExample {
public static void main(String args[]) {
// Regular expression to find digits
String regex = "(\\s)(\\d)(\\s)";
String input = " 1 Name:Radha, age:25 2 Name:Ramu, age:32" + " 3 Name:Rajeev, age:45 4 Name:Raghu, age:35" + " 5 Name:Rahman, age:30";
// คอมไพล์ regular expression
Pattern pattern = Pattern.compile(regex);
// ตรวจสอบว่ามีการจับคู่เกิดขึ้นหรือไม่
if (pattern.matcher(input).find())
System.out.println("Given String contains digits");
else
System.out.println("Given String does not contain digits");
// แยกสตริง
Stream<String> stream = pattern.splitAsStream(input);
Object obj[] = stream.toArray();
for (int i = 0; i < obj.length; i++) {
System.out.println(obj[i]);
}
}
}
Output
Given String contains digits Name:Radha, age:25 Name:Ramu, age:32 Name:Rajeev, age:45 Name:Raghu, age:35 Name:Rahman, age:30