Lớp Mẫu của gói java.util.regex là một biểu diễn đã biên dịch của một biểu thức chính quy.
Phương thức splitAsStream () của lớp này chấp nhận một đối tượng CharSequence, đại diện cho chuỗi đầu vào dưới dạng tham số và tại mỗi trận đấu, nó tách chuỗi đã cho thành một chuỗi con mới và trả về kết quả dưới dạng một luồng chứa tất cả các chuỗi con.
Ví dụ
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";
//Compiling the regular expression
Pattern pattern = Pattern.compile(regex);
//verifying whether match occurred
if(pattern.matcher(input).find())
System.out.println("Given String contains digits");
else
System.out.println("Given String does not contain digits");
//Splitting the string
Stream<String> stream = pattern.splitAsStream(input);
Object obj[] = stream.toArray();
for(int i=0; i< obj.length; i++) {
System.out.println(obj[i]);
}
}
} Đầu ra
Given String contains digits Name:Radha, age:25 Name:Ramu, age:32 Name:Rajeev, age:45 Name:Raghu, age:35 Name:Rahman, age:30