Java 怎么使用模式(Pattern)分割字符串(String)

2019年5月22日18:25:01 评论 105

1.简介

Java 怎么使用模式(Pattern)分割字符串(String)?——请看下文。

2.代码

/**
 * 版权所有 编程十万个怎么办(www.tah1986.com)
 */
public class SplittingStringsWithPattern {
	public static void main(String[] argv) {
		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) {
		System.out.println(input);
		for (Pattern pattern : patterns) {
			System.out.println(pattern.pattern());
		}
		for (int limit : limits) {
			System.out.println(limit);
			for (Pattern pattern : patterns) {
				String[] tokens = pattern.split(input, limit);
				for (String token : tokens) {
					System.out.print("value:" + token);
				}
			}
		}
	}
	private static Pattern[] collectPatterns(String[] argv) {
		List<Pattern> list = new LinkedList<>();
		for (int i = 1; i < argv.length; i++) {
			list.add(Pattern.compile(argv[i]));
		}
		Pattern[] patterns = new Pattern[list.size()];
		list.toArray(patterns);
		return (patterns);
	}
}

3.结果

Java 使用模式(Pattern)分割字符串(String)

4.总结

示例代码演示了 Java 如何使用模式(Pattern)分割字符串(String),具体步骤参见示例代码。

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: