001/**
002 * 
003 */
004package org.openimaj.hardware.serial;
005
006import java.util.Arrays;
007
008
009/**
010 *      Takes incoming data from a serial parser and splits it into multiple
011 *      strings based on a regular expression.
012 * 
013 *  @author David Dupplaw (dpd@ecs.soton.ac.uk)
014 *      
015 *      @created 12 Jul 2011
016 */
017public class RegExParser implements SerialDataParser
018{
019        private String regex = null;
020        
021        private String leftOvers = null;
022        
023        /**
024         *      Construct a new regex parser
025         *  @param regex
026         */
027        public RegExParser( String regex )
028    {
029                this.regex = regex;
030    }
031        
032        /**
033         *  {@inheritDoc}
034         *  @see org.openimaj.hardware.serial.SerialDataParser#parse(java.lang.String)
035         */
036        @Override
037        public String[] parse( String data )
038        {
039                leftOvers = null;
040                
041                String[] bits = data.split( regex );
042                
043                // If the last data item doesn't match our regular expression
044                // then it must've been left over bits
045                if( !bits[bits.length-1].matches( regex ) )
046                {
047                        leftOvers = bits[bits.length-1];
048                        return Arrays.copyOfRange( bits, 0, bits.length-1 );
049                }
050                
051                return bits;
052        }
053
054        /**
055         *  {@inheritDoc}
056         *  @see org.openimaj.hardware.serial.SerialDataParser#getLeftOverString()
057         */
058        @Override
059        public String getLeftOverString()
060        {
061                return leftOvers;
062        }
063
064        /**
065         *      Set the regular expression to use.
066         *  @param regex The regular expression to use
067         */
068        public void setRegEx( String regex )
069    {
070                this.regex = regex;
071    }
072
073        
074}