Java中的Pattern splitAsStream()方法及其示例
java.util.regex包的Pattern类是正则表达式的编译表示。
此类的splitAsStream()方法接受一个CharSequence对象,该对象将输入字符串表示为参数,并且在每次匹配时,它将给定的字符串拆分为一个新的子字符串,并将结果作为包含所有子字符串的流返回。
示例
import java.util.regex.Pattern; import java.util.stream.Stream; public class SplitAsStreamMethodExample { public static void main( String args[] ) { //正则表达式查找数字 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"; //编译正则表达式 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]); } } }
输出结果
Given String contains digits Name:Radha, age:25 Name:Ramu, age:32 Name:Rajeev, age:45 Name:Raghu, age:35 Name:Rahman, age:30