Splitting strings with Pattern - Java Regular Expressions

Java examples for Regular Expressions:Split

Description

Splitting strings with Pattern

Demo Code

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);
  }//from   w  w w. j  a v a  2  s .co  m

  private static void generateTable(String input, Pattern[] patterns,
      int[] limits) {
    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<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);
  }
}

Result


Related Tutorials