Computer >> Máy Tính >  >> Lập trình >> Java

Phương thức chia mẫu () trong Java với các ví dụ

Mẫu lớp 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.

split () phương thức của lớp này chấp nhận CharSequence đối tượng, đạ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 mã thông báo mới và trả về mảng chuỗi chứa tất cả các mã thông báo.

Ví dụ

import java.util.regex.Pattern;
public class SplitMethodExample {
   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:Rajev, age:45";
      //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
      String strArray[] = pattern.split(input);
      for(int i=0; i<strArray.length; i++){
         System.out.println(strArray[i]);
      }
   }
}

Đầu ra

Given String contains digits
Name:Radha, age:25
Name:Ramu, age:32
Name:Rajev, age:45

Phương thức này cũng chấp nhận một giá trị số nguyên đại diện cho số lần mẫu được áp dụng. tức là bạn có thể quyết định độ dài của mảng kết quả bằng cách chỉ định giá trị giới hạn.

Ví dụ

import java.util.regex.Pattern;
public class SplitMethodExample {
   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
      String strArray[] = pattern.split(input, 4);
      for(int i=0; i<strArray.length; i++){
         System.out.println(strArray[i]);
      }
   }
}

Đầu ra

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