提示:您可在线编辑运行本教程的实例 - 运行实例,去试试!
用模式分割字符串
/**来自 时 代 J a v a 公 众 号 - nowjava.com**/ import java.util.regex.Pattern; import java.util.List; import java.util.LinkedList; public class Main { public static void main(String[] argv) throws Exception { String input = "test test zoo"; Pattern space = Pattern.compile(" "); Pattern d = Pattern.compile("d"); Pattern o = Pattern.compile("o"); Pattern[] patterns = { space, d, o }; int limits[] = { 1, 2, 5, -2, 0 }; patterns = collectPatterns(new String[]{"zoo"}); generateTable(input, patterns, limits); } private static void generateTable(String input, Pattern[] patterns, int[] limits) {/**n o w j a v a . c o m**/ System.out.println(input); for (int i = 0; i < patterns.length; i++) { Pattern pattern = patterns[i]; System.out.println( pattern.pattern()); } for (int i = 0; i < limits.length; i++) { int limit = limits[i]; System.out.println(limit); for (int j = 0; j < patterns.length; j++) { Pattern pattern = patterns[j]; String[] tokens = pattern.split(input, limit); for (int k = 0; k < tokens.length; k++) { System.out.print("value:" + tokens[k]); } } } } private static Pattern[] collectPatterns(String[] argv) { List<