Pattern split() 方法及其在 Java 中的示例
java.util.regex 包中的 Pattern 类是正则表达式的编译表示形式。
此类的 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
广告