001package org.biojava.bio.program.tagvalue; 002 003import java.util.regex.Matcher; 004import java.util.regex.Pattern; 005 006import org.biojava.utils.ParserException; 007 008/** 009 * <p> 010 * A ValueChanger.Changer that returns a specific match value using a regex 011 * Pattern. 012 * </p> 013 * 014 * @author Matthew Pocock 015 * @since 1.3 016 */ 017public class RegexChanger 018 implements 019 ChangeTable.Changer 020{ 021 private Pattern pattern; 022 private int matchGroup; 023 024 /** 025 * Create a new RegexChanger with a pattern. 026 * 027 * @param pattern the Pattern used to split values 028 * @param matchGroup the group to pull out - use 0 to pull out the whole match 029 */ 030 public RegexChanger(Pattern pattern, int matchGroup) { 031 this.pattern = pattern; 032 this.matchGroup = matchGroup; 033 } 034 035 public Object change(Object value) 036 throws ParserException { 037 try { 038 Matcher matcher = pattern.matcher(value.toString()); 039 matcher.find(); 040 return matcher.group(matchGroup); 041 } catch (IllegalStateException e) { 042 throw new ParserException( 043 "Could not match " + pattern.pattern() + " to " + value, e 044 ); 045 } 046 } 047} 048