001package org.biojava.bio.program.tagvalue;
002
003import java.util.regex.Matcher;
004import java.util.regex.Pattern;
005
006import org.biojava.utils.ParserException;
007
008public class RegexFieldFinder
009extends SimpleTagValueWrapper {
010  private final Pattern pattern;
011  private final String[] tags;
012  private final boolean inLine;
013
014  /**
015   * Creates a new RegexFiledFinder.
016   *
017   * @param delegate  the TagValueListener to forward events to
018   * @param pattern a Pattern to match to values
019   * @param tags an array of Strings giving tag names for each group in the
020   *        pattern
021   * @param inLine if false, an entire sub-document will be generated for
022   *        the parent tag
023   */
024  public RegexFieldFinder(
025    TagValueListener delegate,
026    Pattern pattern,
027    String[] tags,
028    boolean inLine
029  ) {
030    super(delegate);
031    this.pattern = pattern;
032    this.tags = tags;
033    this.inLine = inLine;
034  }
035
036  public void startTag(Object tag)
037  throws ParserException {
038    if(!inLine) {
039      super.startTag(tag);
040      super.startRecord();
041    }
042  }
043
044  public void endTag()
045  throws ParserException {
046    if(!inLine) {
047      super.endRecord();
048      super.endTag();
049    }
050  }
051
052  public void value(TagValueContext ctxt, Object val)
053  throws ParserException {
054    try {
055      Matcher m = pattern.matcher(val.toString());
056      m.find();
057      
058      for(int i = 0; i < tags.length; i++) {
059        super.startTag(tags[i]);
060        super.value(ctxt, m.group(i + 1));
061        super.endTag();
062      }
063    } catch (IllegalStateException ise) {
064      throw new ParserException("Problem matching " + pattern.pattern() + " to " + val);
065    }
066  }
067}