รูปแบบ คลาสของแพ็คเกจ java.util.regex เป็นการแสดงนิพจน์ทั่วไปที่คอมไพล์แล้ว
split() เมธอดของคลาสนี้ยอมรับ CharSequence วัตถุ แทนสตริงอินพุตเป็นพารามิเตอร์ และในแต่ละการแข่งขัน จะแยกสตริงที่กำหนดออกเป็นโทเค็นใหม่และส่งคืนอาร์เรย์สตริงที่ถือโทเค็นทั้งหมด
ตัวอย่าง
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]); } } }
ผลลัพธ์
Given String contains digits Name:Radha, age:25 Name:Ramu, age:32 Name:Rajev, age:45
เมธอดนี้ยังยอมรับค่าจำนวนเต็มซึ่งแทนจำนวนครั้งที่รูปแบบที่ใช้ นั่นคือ คุณสามารถกำหนดความยาวของอาร์เรย์ผลลัพธ์ได้โดยการระบุค่าขีดจำกัด
ตัวอย่าง
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]); } } }
ผลลัพธ์
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