package org.biojava.bio.program.tagvalue;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * <p>
 * A ValueChanger.Splitter that splits a line of text using a regular
 * expression, returning one value per match.
 * </p>
 *
 * <p>
 * A list of values is generated by effectively executing:
 * <pre>
 * matcher = pattern.matcher(value.toString());
 *
 * while(matcher.find()) {
 *   values.add(matcher.group(matchGroup);
 * }
 * </pre>
 * </p>
 *
 * @author Matthew Pocock
 * @since 1.3
 */
public class RegexSplitter
  implements
    ChangeTable.Splitter
{
  private Pattern pattern;
  private int matchGroup;

  /**
   * Create a new RegexSplitter with a pattern.
   *
   * @param pattern  the Pattern used to split values
   * @param matchGroup the group to pull out - use 0 to pull out the whole match
   */
  public RegexSplitter(Pattern pattern, int matchGroup) {
    this.pattern = pattern;
    this.matchGroup = matchGroup;
  }
  
  public List split(Object value) {
    Matcher matcher = pattern.matcher(value.toString());
    
    List result = new ArrayList();
    while(matcher.find()) {
      result.add(matcher.group(matchGroup));
    }
    
    return result;
  }
}

