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[] ) {
      //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]);
      }
   }
}

輸出

Given String contains digits
Name:Radha, age:25
Name:Ramu, age:32
Name:Rajeev, age:45
Name:Raghu, age:35
Name:Rahman, age:30

更新於: 20-Nov-2019

298 瀏覽量

開啟你的 職業

完成課程獲得認證

立即開始
廣告